SpringSecurity放入验证对象

关于SpringSecurity理解

启动类-》配置类-》信息验证

启动类代码

@SpringBootApplication
public class Demo21Pagetool1Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo21Pagetool1Application.class, args);
    }

}

配置类代码

@Configuration
public class ConfigurationBean {
	@Bean
	UserService userService(@Autowired UserServiceImpl bean) {
		return bean;
	}
	
	/*@Bean
	UserDetailsService (bean名称)userDetailsService(@Autowired CustomUserDetailsService bean) {
		return bean;
	}*/
	
	@Bean
	public PasswordEncoder passwordEncoder() {
		//return NoOpPasswordEncoder.getInstance();
		System.out.println("passwordEncoder");
		return new BCryptPasswordEncoder();

	}
}


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationTwo extends WebSecurityConfigurerAdapter{
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/*@Autowired
	private FailureAuthenticationHandler failureHandler;

	@Autowired
	private SuccessAuthenticationHandler successHandler;*/
	/*@EnableWebSecurity是Spring Security用于启用Web安全的注解。
	 * 典型的用法是该注解用在某个Web安全配置类上(实现了接口WebSecurityConfigurer
	 * 或者继承自WebSecurityConfigurerAdapter)。典型的使用例子如下 :*/
	/*
	用来处理身份认证的类是 AuthenticationManager,我们也称之为认证管理器*/
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		System.out.println("configure");
		auth.userDetailsService(userDetailsService)// 设置自定义的userDetailsService
				.passwordEncoder(passwordEncoder);
	}
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
        .antMatchers("/login/Login","/login/error") // 不需要登录就可以访问
        .permitAll()
        //.antMatchers("/user/**").hasAnyRole("USER") // 需要具有ROLE_USER角色才能访问
        //.antMatchers("/admin/**").hasAnyRole("ADMIN") // 需要具有ROLE_ADMIN角色才能访问
        .anyRequest().authenticated()
        .and()
            .formLogin()
            .loginPage("/login/Login") // 设置登录页面
//            .loginProcessingUrl("/login")
            .failureForwardUrl("/login/error")
            .successForwardUrl("/login/success") // 设置登录成功后跳转的页面
        ;

    }
	
}

验证代码

@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
   @Autowired
   private UserService userService;
   
   
   @Override
   public UserDetails loadUserByUsername(@Param("username")String username) throws UsernameNotFoundException{
   	// TODO Auto-generated method stub
   	System.out.println("UserDetailsService");
   	String detailsname = userService.getUsername(username);
   	if(detailsname == null) {
   		throw new UsernameNotFoundException("用户名"+detailsname+"没有发现"); 
   	}
   	List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
   	
   	//获取用户密码进行验证
   	//String detailspassword =BCrypt.hashpw(userService.getUserPassword(username), BCrypt.gensalt()) ;
   	String detailspassword = userService.getUserPassword(username);
   	
   	
   	
   	if(detailspassword == null) {
   		try {
   			System.out.println("密码错误");
   			throw new Exception("用户密码错误");
   		} catch (Exception e) {
   			// TODO Auto-generated catch block
   			System.out.println("密码错误");
   			e.printStackTrace();
   		}
   	}
   	System.out.println("密码正确");
   	//验证权限放入接口实现simplegrantedAuthority
   	GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(userService.getRole(username));
   	grantedAuthorities.add(grantedAuthority);
   	
   	//验证用户实现了UserDetails接口,UserDetails用于返回验证用户名验证密码验证权限
   	User detailsUser = new User(detailsname, userService.getUserPassword(username), grantedAuthorities);
   	//$2a$10$v9hKV08rUMsWXQsG0R7AWu36voTEngg9SGcCwzVqgv8D39w9Ujk1u
   	System.out.println(detailsUser.getPassword());
   	return detailsUser;
   }
   
}

其他代码

@Mapper
public interface UserMapper {
	
	@Select("select username from sys_user where username=#{username}")
	String getUsername(@Param("username") String username);
	
	@Select("select password from sys_user where username=#{username}")
	String getUserPassword(@Param("username") String username);

	@Select("select role from sys_user where username=#{username}")
	String getUserRole(@Param("username") String username);
	
	@Select("select *from sys_user where username=#{username} and password=#{password}")
	SysUser getSysUser(@Param("username") String username,@Param("password")String password);
}

public interface UserService {
	SysUser getSysUser(SysUser sysUser);
	String getUsername(String username);
	String getRole(String username);
	String getUserPassword(String username);
}
@Service
public class UserServiceImpl implements UserService{
	@Autowired 
	private UserMapper userMapper;
	
		
	@Override
	public SysUser getSysUser(SysUser sysUser) {
		// TODO Auto-generated method stub
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String password = passwordEncoder.encode(sysUser.getUsername());
		return userMapper.getSysUser(sysUser.getUsername(), password);
	}



	@Override
	public String getUsername(String username) {
		// TODO Auto-generated method stub
		return userMapper.getUsername(username);
	}



	@Override
	public String getRole(String username) {
		// TODO Auto-generated method stub
		return userMapper.getUserRole(username);
	}



	@Override
	public String getUserPassword(String username) {
		// TODO Auto-generated method stub
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String password = passwordEncoder.encode(userMapper.getUserPassword(username));
		return password;
	}

}

@Data
public class SysUser {
private int id;
private String username;
private String password;
private String role; 
}

页面验证

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div th:if="${error}">
    用户名或密码错误
</div>
<div th:if="${logout}">
    你已经退出
</div>
<form th:action="@{Login}" method="post">
    <div><label> 账号 : <input type="text" name="username"/> </label></div>
    <div><label> 密码 : <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登录"/></div>
</form>
</body>
</html>
Created with Raphaël 2.2.0 开始 验证信息 userDetailsService? successPage 结束 errorPage yes no
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值