/** * Expects the incoming authentication request to have a principal value that is an access token value (e.g. from an * authorization header). Loads an authentication from the {@link ResourceServerTokenServices} and checks that the * resource id is contained in the {@link AuthorizationRequest} (if one is specified). Also copies authentication * details over from the input to the output (e.g. typically so that the access token value and request details can * be reported later). * * @param authentication an authentication request containing an access token value as the principal * @return an {@link OAuth2Authentication} * * @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication) */ public Authentication authenticate(Authentication authentication)throws AuthenticationException {
if (authentication == null) { thrownewInvalidTokenException("Invalid token (token not found)"); } // token 换用户身份信息 Stringtoken= (String) authentication.getPrincipal(); OAuth2Authenticationauth= tokenServices.loadAuthentication(token); if (auth == null) { thrownewInvalidTokenException("Invalid token: " + token); } // 资源ID匹配 Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds(); if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) { thrownewOAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")"); } // 尝试检查请求方oauth clientId 的合法性,取决于是否注入了ClientDetailsService checkClientDetails(auth);
if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) { OAuth2AuthenticationDetailsdetails= (OAuth2AuthenticationDetails) authentication.getDetails(); // Guard against a cached copy of the same details if (!details.equals(auth.getDetails())) { // Preserve the authentication details from the one loaded by token services details.setDecodedDetails(auth.getDetails()); } } auth.setDetails(authentication.getDetails()); auth.setAuthenticated(true); return auth;