版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l1336037686/article/details/81153907
实现获取提交表单信息,匹配数据库完成登录。
配置类
/**
* Security配置类
*
* @author LGX_TvT
* @date 2018-09-19 21:11
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("userDetailServicImpl")
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//设置相应资源对应的角色访问权限
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("User1")
.antMatchers("/level2/**").hasRole("User2")
.antMatchers("/level3/**").hasRole("User3")
.antMatchers("/**").hasRole("User1")
.and()
.formLogin() //设置登陆
.and()
.logout(); //设置退出
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}
登陆验证
/**
* 登陆验证
* @author LGX_TvT
* @date 2018-09-20 8:55
*/
@Service
public class UserDetailServicImpl implements UserDetailsService{
//获取HttpServletRequest
@Autowired
private HttpServletRequest request;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//创建BCrypt加密对象
BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
//获取登录密码
String password = request.getParameter("password");
//可以通过username获取数据库角色进行登录判断
//使用bcpe.matches判断密码是否相同
if("user1".equals(username) && bcpe.matches(password,bcpe.encode("123456"))){
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_User1"));
authorities.add(new SimpleGrantedAuthority("ROLE_User2"));
return new User(username,bcpe.encode(password),authorities);
}else {
throw new UsernameNotFoundException("用户不存在");
}
}
}