shiro登陆认证

1.LoginController

@RequestMapping(method = RequestMethod.POST)
public String login(User user, HttpServletRequest request) {
    try {
        ubject subject = SecurityUtils.getSubject();
         UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        token.setRememberMe(true);
        String vcode = request.getParameter("verifyCode");
        String verifyCode = subject.getSession().getAttribute(Global.SESSION_SECURITY_CODE).toString();

        if (vcode.equals(verifyCode)) {
            subject.login(token); //启动认证
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "modules/sys/sysLogin";
    }
    return "redirect:index";
}            

2.AuthenticationInfo

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
        // 令牌——基于用户名和密码的令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        // 令牌中可以取出用户名
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());

        // 让shiro框架去验证账号密码
        if (!StringUtils.isEmpty(username)) {

            User record = new User();
            record.setLoginName(username);
            
            User user = userService.queryOne(record);
            
            if (null != user) {
                String pwdEncrypt = CipherUtil.createPwdEncrypt(password, username);
                if (user.getPassword().equals(pwdEncrypt)) {
                    AuthenticationInfo info = new SimpleAuthenticationInfo(user.getLoginName(), password,
                            getName());
                    if (info != null) {
                        UserUtils.setSession(Global.SESSION_USER, user);
                    }
                    return info;
                } else {
                    throw new IncorrectCredentialsException(); /* 错误认证异常 */
                }
            } else {
                throw new UnknownAccountException(); /* 找不到帐号异常 */
            }
        } else {
            throw new AuthenticationException();
        }
    }

 

posted @ 2017-08-18 22:04  方大帝的博客  阅读(319)  评论(0编辑  收藏  举报