Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

    Spring-security-oauth2的版本是2.0

    如下图1所示,继承了Filter,还继承了InitializingBean,这个与SpringIOC有关,在创建Bean的时候,会调用afterPropertiesSet方法,进行一些判断或者初始化之类的操作

    

 

                   Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter_第1张图片

                                                                             图1

    我们重点来看下doFilter方法,如下List-1

    List-1 OAuth2AuthenticationProcessingFilter的doFilter方法

	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的value

Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter_第2张图片

                                                                             图2

    图2中的步骤2~5,从头部取出token,调用OAuth2AuthenticationManager,用token去进行一系列的处理,如果token有效,那么将OAuth2Autentication取出放到SecurityContext中,有OAuth2Authentication在SecurityContext中表明用户处于登录状态。

转载于:https://my.oschina.net/u/2518341/blog/3014174

你可能感兴趣的:(Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter)