开发技术 / Technology
    您的当前位置:网站首页 > 行业洞察 > 开发技术

    如何使用Shiro实现用户注册成功后自动登录?

    日期:2015年4月8日  作者:zhjw  来源:互联网    点击:1204

    10

    如何使用Shiro实现用户注册成功后自动登录?15

    之前用户注册后是先跳到登录页面: 
    Java代码  收藏代码
    1. @RequestMapping(method = RequestMethod.POST)  
    2. public String register(@Valid User user, RedirectAttributes redirectAttributes) {  
    3.     accountService.registerUser(user);  
    4.     redirectAttributes.addFlashAttribute("username",  
    5. user.getLoginName());  
    6.     return "redirect:/login";  
    7. }  

    现在要求用户注册成功后自动登录,改写如下: 
    Java代码  收藏代码
    1. @RequestMapping(method = RequestMethod.POST)  
    2. public String register(@Valid User user, RedirectAttributes redirectAttributes) {  
    3.     accountService.registerUser(user);  
    4.     UsernamePasswordToken token = new UsernamePasswordToken();  
    5.     token.setUsername(user.getLoginName());  
    6.     token.setPassword(user.getPassword().toCharArray());  
    7.     SecurityUtils.getSubject().login(token);  
    8.     return "redirect:/";  
    9. }  

    结果报错: 
    Java代码  收藏代码
    1. org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - user01, rememberMe=false] did not match the expected credentials.  

    问题补充:问题解决了,改写成token.setPassword(user.getPlainPassword().toCharArray()); 就可以了。因为我的user的plainPassword是明文,user的password是hash。