Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter

Springsecurity-oauth2之OAuth2AuthenticationProcessingFilter

xym01 1 2019-02-24 19:38 

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中表明用户处于登录状态。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值