在整合springsecurity时遇到好几个问题,自动配置登录,下线,注销用户的操作,数据基于mybatis,模版引擎用的thymeleaf+bootstrap。

 一、认证时密码的加密(passwordEncoder)原理如下

  •      其中 MD5Util是自定义密码加密工具类,随便写(注意添加盐值),注意点:理解匹配密码这个过程
//认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(new  PasswordEncoder() {
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                //匹配   =================将用户表单登录的密码和encodedPasswor(这个值是从MyUserDetailService那边封装过来的))对比=================
                return encodedPassword.equals(encode(rawPassword));
            }
            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String) rawPassword);
            }
        });
        
    }
  • MyUserDetailService是一个实现了UserDetailsService(springsecurity本身的接口)的方法,在这里面实现认证的数据查询及其登录用户权限查询封装。
  • 注意点:理解权限的赋予,即当前用户在这里就已经将所有的角色封装到springsecurity本身的User中了,但是在这里并没有认证成功,单纯的进行封装而已
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    private SessionRegistry sessionRegistry;
    
    @Override
    public UserDetails loadUserByUsername(String username)  {
        
        if (username==null || username.equals("")) {
             throw new UsernameNotFoundException("用户名不存在");
        }
        
        Sys_User user=userService.getUserByName(username);
        
         //获得所有登录用户的信息
         List<Object> list =sessionRegistry.getAllPrincipals();
         for (Object object : list) {
             if (((User)object).getUsername().equals(user.getUsername())) {
                 throw new SessionAuthenticationException("当前用户已经在线,登录失败");
             }
             System.out.println("getAllPrincipals的遍历"+((User)object).getUsername());
         }
        
        //得到当前登录用户的信息
         List<SimpleGrantedAuthority> authorities = new ArrayList<>();
         
         for (Role role : user.getRoles()) {
             //将得到的角色封装  在后面页面认证成功后会用到
               authorities.add(new SimpleGrantedAuthority(role.getRolename()));
               System.out.println("拥有的角色:"+role.getRolename());
            }
        return  new User(user.getUsername(), user.getPassword(), authorities);
    }

}
View Code

相关文章:

  • 2022-02-10
  • 2021-12-20
  • 2021-12-07
  • 2022-01-17
  • 2022-01-03
  • 2021-12-30
猜你喜欢
  • 2021-05-11
  • 2020-10-31
  • 2022-01-02
  • 2022-12-23
  • 2021-09-19
  • 2021-11-05
  • 2021-07-04
相关资源
相似解决方案