Spring-security-oauth2的版本是2.0java
以下圖1所示,繼承了Filter,還繼承了InitializingBean,這個與SpringIOC有關,在建立Bean的時候,會調用afterPropertiesSet方法,進行一些判斷或者初始化之類的操做less
圖1ui
咱們重點來看下doFilter方法,以下List-1debug
List-1 OAuth2AuthenticationProcessingFilter的doFilter方法code
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { Authentication authentication = tokenExtractor.extract(request); if (authentication == null) { if (stateless && isAuthenticated()) { if (debug) { logger.debug("Clearing security context."); } SecurityContextHolder.clearContext(); } if (debug) { logger.debug("No token in request, will continue chain."); } } else { request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal()); if (authentication instanceof AbstractAuthenticationToken) { AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication; needsDetails.setDetails(authenticationDetailsSource.buildDetails(request)); } Authentication authResult = authenticationManager.authenticate(authentication); if (debug) { logger.debug("Authentication success: " + authResult); } eventPublisher.publishAuthenticationSuccess(authResult); SecurityContextHolder.getContext().setAuthentication(authResult); } } catch (OAuth2Exception failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request failed: " + failed); } eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A")); authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed)); return; } chain.doFilter(request, response); }
處理的時序圖以下圖2,步驟4會從HttpServletRequest的頭部取出name爲Authorization的valueblog
圖2繼承
圖2中的步驟2~5,從頭部取出token,調用OAuth2AuthenticationManager,用token去進行一系列的處理,若是token有效,那麼將OAuth2Autentication取出放到SecurityContext中,有OAuth2Authentication在SecurityContext中代表用戶處於登陸狀態。token