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(""));

    }

就這樣,測試成功了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章