Spring Security Oauth2 如何鉴别Token是否有效

转载:https://blog.csdn.net/zimou5581/article/details/101051416

重点

当oauth2请求(Authorization请求头中Bearer协议的 access_token)进行访问时,会进入OAuth2AuthenticationProcessingFilter之中

public class OAuth2AuthenticationProcessingFilter implements Filter, InitializingBean {
    // ... 其他变量 和 方法
    
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain){
    
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
    
        try {
            //从请求中取出身份信息,将access_token 放入principal变量
            Authentication authentication = tokenExtractor.extract(request);
    
            if (authentication == null) {
                // token信息为null,SecurityContextHolder 清空上下文
            }
            else {
                // request请求对象 放入authentication对象中
                request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
                if (authentication instanceof AbstractAuthenticationToken) {
                    AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                    needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
                }
                // 验证token身份信息
                Authentication authResult = authenticationManager.authenticate(authentication);
                eventPublisher.publishAuthenticationSuccess(authResult);
                //将身份信息绑定到SecurityContextHolder中
                SecurityContextHolder.getContext().setAuthentication(authResult);
            }
        }
        catch (OAuth2Exception failed) {
            // SecurityContextHolder 清空上下文, 然后直接返回
            return;
        }
        chain.doFilter(request, response);
    }
}
原文地址:https://www.cnblogs.com/cq-yangzhou/p/13036292.html