1. 程式人生 > >springSecurity手動登錄

springSecurity手動登錄

根據 請求 並且 ESS 過程 認證方式 cep 用戶 ets

springSecurity 每種認證方式都要寫一大推類

1.要寫Token封裝認證信息

2.要寫UserDetailsService的實現獲取用戶信息

3.要寫provider調用UserDetailsService並且告訴AuthenticationManager他能認證哪種token

4.要寫filter去攔截用戶請求,獲取用戶提交的表單數據,交給AuthenticationManager選擇一個provider去認證

5.把filter與provider註入一些必要屬性交給總配置

-----------------------------------------------------------------------------------------------------------------------------------------------------

如果不想這麽繁瑣,簡單暴力的

1、用戶名、密碼組合生成一個Authentication對象(也就是UsernamePasswordAuthenticationToken對象)。

2、生成的這個token對象會傳遞給一個AuthenticationManager對象用於驗證。

3、當成功認證後,AuthenticationManager返回一個Authentication對象。

4、接下來,就可以調用

SecurityContextHodler.getContext().setAuthentication(…)

這個過程手動進行

@Controller
public class SecurityController {



    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;


    @Resource
    private AuthenticationManager authenticationManager;


    @Autowired
    private UserSecurityService userSecurityService;


    @RequestMapping("/shoudongdenglu")
    public  void shoudongdenglu(HttpServletRequest request,HttpServletResponse response)
        throws IOException, ServletException {

        //根據用戶名username加載userDetails
        UserDetails userDetails = userSecurityService.loadUserByUsername("ld");
        //根據userDetails構建新的Authentication,這裏使用了
        //PreAuthenticatedAuthenticationToken當然可以用其他token,如UsernamePasswordAuthenticationToken
        PreAuthenticatedAuthenticationToken authentication =
            new PreAuthenticatedAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities());
        //設置authentication中details
        authentication.setDetails(new WebAuthenticationDetails(request));
        //存放authentication到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        HttpSession session = request.getSession(true);
        //在session中存放security context,方便同一個session中控制用戶的其他操作
        session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());

      // response.sendRedirect("/");


        myAuthenticationSuccessHandler.onAuthenticationSuccess(request,response,authentication);

        return;

    }

}

  

springSecurity手動登錄