Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter

我们两清 提交于 2020-03-21 22:27:17

3 月,跳不动了?>>>

    Spring-security-oauth2的版本是2.0

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

    

 

                   

                                                                             图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

                                                                             图2

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!