spring security 3.1注册后自动登录

网上搜索一大圈,最后发现http://www.ke-cai.net/2010/11/auto-login-after-successful.html里讲述的是最接近答案的,但一测试,发现验证是通过了,session却没有保存,接着再搜,发现了一篇文章说到了这个问题,http://stackoverflow.com/questions/5428654/spring-security-auto-login-not-persisted-in-httpsession,按照它提供的解决方法发现session能保存了。

最后要解决的一件事是验证失败处理,上面两篇文章都没说,参考spring security document解决了,最后代码如下:

在controller里边声明AuthenticationManager变量,这个是关键点:

    @Autowired
    @Qualifier("org.springframework.security.authenticationManager")//编辑软件会提示错误
    protected AuthenticationManager authenticationManager;

然后是当注册成功后的代码:

@RequestMapping(value = "/registermyuser")
    public ModelAndView registeruser(
            Locale locale,HttpServletRequest request)
    {
        System.out.println("register user");

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                "heda", "111111");

        //request.getSession();

        try{
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager
                .authenticate(token);

        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        }
        catch( AuthenticationException e ){
            System.out.println("Authentication failed: " + e.getMessage());
            return new ModelAndView(new RedirectView("register"));
        }
        
        return new ModelAndView(new RedirectView(""));

    }

就这样,测试成功了。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值