shiro 加盐认证

      
    
        
        
        
        
        
        
        
        
        
            
                
                
                
                /images/**=anon
                /js/**=anon
                /styles/**=anon

                
                /logout.action=logout

                
                /** = authc
                
            
        
    
    
        
       

 
        
    

    
    
        
        
    

自定义Realm

public class CustomRealm extends AuthorizingRealm {

    //注入service
    @Autowired
    private SysService sysService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    // 设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1 从token中取出用户名
        String userCode = (String) token.getPrincipal();

        //2 数据库中获取
        SysUser  sysUser = sysService.findSysUserByUserCode(userCode);

        if (sysUser == null) {
            return null;
        }

        String password = sysUser.getPassword();
        String salt = sysUser.getSalt();


        ActiveUser activeUser = new ActiveUser();
        activeUser.setUserid(sysUser.getId());
        activeUser.setUsercode(sysUser.getUsercode());
        activeUser.setUsername(sysUser.getUsername());

        List menuLists = null;
        try {
            menuLists = sysService.findMenuListByUserId(sysUser.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        activeUser.setMenus(menuLists);

        // password
        // 如果查询到了,返回AuthenticationInfo
        // 如果密码不匹配,抛出IncorrectCredentialsException
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser,
                sysUser.getPassword(), ByteSource.Util.bytes(salt), this.getName());

        return simpleAuthenticationInfo;
    }
}

login.action处理

  @RequestMapping(value = "login.action")
    public String login(HttpServletRequest request) throws Exception {

        //登录失败从request中获取认证异常信息  shiroLoginFailure 就是shiro异常类的全限定名
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        //根据shiro返回的异常类型路径判断,抛出指定异常信息
        if (exceptionClassName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                throw new CustomException("账号不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                throw new CustomException("账号密码错误");
            } else {
                throw new Exception();
            }
        }
        ////此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
        //login.jsp界面
        return "login";
    }

你可能感兴趣的:(shiro 加盐认证)