如何访问 oauth2 访问令牌和用户信息

Posted

技术标签:

【中文标题】如何访问 oauth2 访问令牌和用户信息【英文标题】:How to access oauth2 access token and user information 【发布时间】:2021-08-31 14:14:12 【问题描述】:

我正在尝试使用 oauth2 springboot 来使用 fitbit 数据, 在这个过程中,我可以获得授权码和 access_token,但问题在于 userInfoUri: https://api.fitbit.com/1/user/-/profile.json 和 userNameAttribute: user userinfoUri 给出以下响应。

   "user": 
    "aboutMe":<value>,
    "avatar":<value>,
    "avatar150":<value>,
    "avatar640":<value>,
    "city":<value>,
    "clockTimeDisplayFormat":<12hour|24hour>,
    "country":<value>,
    "dateOfBirth":<value>,
    "displayName":<value>,
    "distanceUnit":<value>,
    "encodedId":<value>,
    "foodsLocale":<value>,
    "fullName":<value>,
    "gender":<FEMALE|MALE|NA>,
    "glucoseUnit":<value>,
    "height":<value>,
    "heightUnit":<value>,
    "locale":<value>,
    "memberSince":<value>,
    "offsetFromUTCMillis":<value>,
    "startDayOfWeek":<value>,
    "state":<value>,
    "strideLengthRunning":<value>,
    "strideLengthWalking":<value>,
    "timezone":<value>,
    "waterUnit":<value>,
    "weight":<value>,
    "weightUnit":<value>

由于我们可以观察输出,我们找不到用户名,但我们可以在用户中找到全名,现在我想将用户名设置为全名,我需要在使用以下代码进行身份验证后获取 access_token

                OAuth2AuthorizedClient user1 = clientService.loadAuthorizedClient("fitbit", authentication.getUsername() );
    org.springframework.security.oauth2.core.OAuth2AccessToken accessToken = user1.getAccessToken();
            return accessToken.getTokenValue();

如果这不是建议或提供示例的方式。

下面是我的 .yml 代码

                           spring:
  security:
      oauth2:
        client:
          registration:
             fitbit:
               clientId: XXXXXX
               clientSecret: XXXXXXXXXXXXX
               clientAuthenticationMethod: post
               authorizationGrantType: authorization_code
               redirectUri: http://localhost:8080/oauth2/code/fitbit
               scope: activity,profile
              clientName: fitbit
      provider:
        fitbit:
          authorizationUri: https://www.fitbit.com/oauth2/authorize
          tokenUri: https://api.fitbit.com/oauth2/token?
          userInfoUri: https://api.fitbit.com/1/user/-/profile.json
          userNameAttribute: user

这里是安全配置:

                                @Configuration
  @EnableWebSecurity
        public class SecurityFor extends WebSecurityConfigurerAdapter 

@Autowired
UserDetailsModel userdetails;

@Override
protected void configure(HttpSecurity http) throws Exception 
    http
        .authorizeRequests().antMatchers("/home","/login","/oauth2/code/fitbit" ,"/test/login/**","/callback/", 
       "/webjars/**", "/error**", "**/oauth2/**")
        .permitAll()
            .anyRequest().authenticated()
            .and()
        .oauth2Login().authorizationEndpoint()
        .baseUri("/oauth2/authorize/fitbit")
        .and()
        .redirectionEndpoint()
        .baseUri("/oauth2/code/fitbit")
        .and()
            .tokenEndpoint()
                .accessTokenResponseClient(accessTokenResponseClient())
            .and().userInfoEndpoint().userService(userdetails);

@Bean
 public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient()
        DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = 
          new DefaultAuthorizationCodeTokenResponseClient(); 
        
        accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter()); 

        OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = 
          new OAuth2AccessTokenResponseHttpMessageConverter(); 
        tokenResponseHttpMessageConverter.setTokenResponseConverter(new 
         OAuth2AccessTokenResponseConverterWithDefaults()); 
        RestTemplate restTemplate = new RestTemplate(Arrays.asList(
          new FormHttpMessageConverter(), tokenResponseHttpMessageConverter)); 
        restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); 
        
        accessTokenResponseClient.setRestOperations(restTemplate); 
        return accessTokenResponseClient;
    
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> 
       authorizationCodeTokenResponseClient() 
    OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter =
            new OAuth2AccessTokenResponseHttpMessageConverter();

    tokenResponseHttpMessageConverter.setTokenResponseConverter(new 
         OAuth2AccessTokenResponseConverterWithDefaults());

    RestTemplate restTemplate = new RestTemplate(Arrays.asList(
            new FormHttpMessageConverter(), tokenResponseHttpMessageConverter));
    
    restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

    DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = new 
       DefaultAuthorizationCodeTokenResponseClient();
    
    tokenResponseClient.setRestOperations(restTemplate);

    return tokenResponseClient;

CustomRequestEntityConverter.java

               public class CustomRequestEntityConverter implements Converter<OAuth2AuthorizationCodeGrantRequest, 
   RequestEntity<?>> 
 private OAuth2AuthorizationCodeGrantRequestEntityConverter defaultConverter;

public CustomRequestEntityConverter() 
    defaultConverter = new OAuth2AuthorizationCodeGrantRequestEntityConverter();
   
@Override
public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest req) 
    // TODO Auto-generated method stub
    
     RequestEntity<?> entity = defaultConverter.convert(req);
     
        MultiValueMap<String, String> params = (MultiValueMap<String,String>) entity.getBody();
        String a="clientid:cliensecert";
       
        String code = Base64.getEncoder().encodeToString(a.getBytes());
        HttpHeaders g1=new HttpHeaders();
        g1.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        g1.add(HttpHeaders.AUTHORIZATION,"Basic "+code);
       
   return new RequestEntity<>(params, g1, 
              entity.getMethod(), entity.getUrl());  


  

OAuth2AccessTokenResponseConverterWithDefaults.java

              public class OAuth2AccessTokenResponseConverterWithDefaults implements Converter<Map<String, String>, 
  OAuth2AccessTokenResponse> 
private static final Set<String> TOKEN_RESPONSE_PARAMETER_NAMES = Stream.of(
        OAuth2ParameterNames.ACCESS_TOKEN,
        OAuth2ParameterNames.TOKEN_TYPE,
        OAuth2ParameterNames.EXPIRES_IN,
        OAuth2ParameterNames.REFRESH_TOKEN,
        OAuth2ParameterNames.SCOPE).collect(Collectors.toSet());
   @Autowired
   UserDetailsModels user_details;
private OAuth2AccessToken.TokenType defaultAccessTokenType = OAuth2AccessToken.TokenType.BEARER;

@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) 
    System.out.println(OAuth2ParameterNames.ACCESS_TOKEN);
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
    System.out.println(accessToken);
    //user_details.setToken(accessToken);
    / /System.out.println(user_details.getToken());
    OAuth2AccessToken.TokenType accessTokenType = this.defaultAccessTokenType;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(
            tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) 
        
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    

    long expiresIn = 0;
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) 
        try 
            
            expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
         catch (NumberFormatException ex)  
    

    Set<String> scopes = Collections.emptySet();
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) 
        String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
        scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet());
    

    Map<String, Object> additionalParameters = new LinkedHashMap<>();
    tokenResponseParameters.entrySet().stream()
            .filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
            .forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));

    return OAuth2AccessTokenResponse.withToken(accessToken)
            .tokenType(accessTokenType)
            .expiresIn(expiresIn)
            .scopes(scopes)
            .additionalParameters(additionalParameters)
            .build();


public final void setDefaultAccessTokenType(OAuth2AccessToken.TokenType defaultAccessTokenType) 
    Assert.notNull(defaultAccessTokenType, "defaultAccessTokenType cannot be null");
    this.defaultAccessTokenType = defaultAccessTokenType;



  

UserDetailsModel.java

  @Service
  public class UserDetailsModel extends DefaultOAuth2UserService

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException 
    OAuth2User user = super.loadUser(userRequest);
    Map<String, Object> attributes = user.getAttributes();
    System.out.println(attributes.keySet());
    Set<GrantedAuthority> authorities = new HashSet();
    String d=(String) ((Map<String, Object>) attributes.get("user")).get("fullName");
    System.out.println(d);
    
     
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    
    return new DefaultOAuth2User(authorities, attributes, "user");

webclient.java

                      @Configuration
       public class WebClientConfig 

@Bean
public WebClient webClient(ClientRegistrationRepository clientRegistrationRepository,
                            OAuth2AuthorizedClientRepository authorizedClientRepository) 
    
    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new 
      ServletOAuth2AuthorizedClientExchangeFilterFunction(
            clientRegistrationRepository, authorizedClientRepository);
    System.out.println(oauth2.oauth2Configuration());
    
    return WebClient.builder()
            .apply(oauth2.oauth2Configuration())
            .build();

休息控制器

        @RestController
public class FitibitRestOauth2 
 WebClient webClient;
 @Autowired
 private OAuth2AuthorizedClientService clientService;
 
    public void MainController(WebClient webClient) 
        this.webClient = webClient;
    
    
    @GetMapping("/oauth2/code/fitbit")
    public String working() 
        return "working";
    
    @GetMapping("/")
    public String data(Authentication authentication,OAuth2AuthenticationToken authentication1,OAuth2Authentication 
    auth) 
        //System.out.println(authentication1.getPrincipal().getAuthorities());
        /*System.out.println("@@@@@@@@@@@@@@@@@@@@@@@22");
         OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
        //token
         System.out.println(details);
         System.out.println("************8*************");
        String accessToken = details.getTokenValue();
        System.out.println(accessToken);
        //reference
         
         */
     /*   org.springframework.security.oauth2.common.OAuth2AccessToken accessToken1 = 
     tokenStore.readAccessToken(details.getTokenValue());
       // clientid
        String clientId = auth.getOAuth2Request().getClientId();
        OAuth2AuthorizedClient user1 = clientService.loadAuthorizedClient("fitbit", authentication.getUsername() );
        */
        /*System.out.println("@@@@@@"+user1);
        org.springframework.security.oauth2.core.OAuth2AccessToken accessToken = user1.getAccessToken();
        //DefaultOidcUser user= (DefaultOidcUser)authentication.getPrincipal();
        //OAuth2AuthenticatedPrincipal user =(OAuth2AuthenticatedPrincipal) authentication.getPrincipal();
        System.out.println(accessToken.getTokenValue());*/
        //OAuth2AuthorizedClient user1 = clientService.loadAuthorizedClient("fitbit", authentication.getUsername() );
        //org.springframework.security.oauth2.core.OAuth2AccessToken accessToken = user1.getAccessToken();
        //org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser user= 
     (DefaultOidcUser)authentication.getPrincipal();
    //  OAuth2AuthenticatedPrincipal user =(OAuth2AuthenticatedPrincipal) authentication.getPrincipal();
        //System.out.println(accessToken.getTokenValue());

        
        
        org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails   auth1 = 
   (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails(); 
        String accessToken1 = auth1.getTokenValue();
        return "hai";
    

我在 restcontroller 中获取访问令牌:

            Current user principal is not of type [org.springframework.security.oauth2.provider.OAuth2Authentication]: 
     OAuth2AuthenticationToken [Principal=Name: [age=52, ambassador=false, autoStrideEnabled=true, 
  avatar=https://static0.fitbit.com/images/profile/default.png, avatar150=https://static0.fitbit.com/images/profile/default.png, 
   avatar640=https://static0.fitbit.com/images/profile/Profile_640.png, averageDailySteps=4879, challengesBeta=true, 
 clockTimeDisplayFormat=12hour, corporate=false, corporateAdmin=false, dateOfBirth=1969-02-15, displayName=smnah, 
 displayNameSetting=name, distanceUnit=en_US, encodedId=98CJ9M, features=exerciseGoal=true, firstName=smnah, 
fullName=smnah, gender=FEMALE, glucoseUnit=en_US, height=160.0, heightUnit=en_US, isBugReportEnabled=false, 
  shareImage640px=https://badges.fitbit.com/images/badges_new/386px/shareLocalized/en_US/badge_daily_floors10.png, 
 shareText=I climbed 10 flights of stairs and earned the Happy Hill badge! #Fitbit, shortDescription=10 floors, 
 strideLengthWalking=66.10000000000001], weight=0.0, weightUnit=en_US], Credentials=[PROTECTED], 
  Authenticated=true, 
   Details=WebAuthenticationDetails [RemoteIpAddress=x.x.x.x.x.x.x., SessionId=xxxxxxxxxxxxxxxxxxx],
   Granted Authorities=[ROLE_USER]]
at 
  org.springframework.web.servlet.mvc.method.annotation.
   ServletRequestMethodArgumentResolver.resolveArgument(ServletRequestMethodArgumentResolver.java:169) ~[spring- 
  webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method
   .annotation.ServletRequestMethodArgumentResolver.resolveArgument(ServletRequestMethodArgumentResolver.java:124) ~ 
   [spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.
  HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~ 
  [spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support
   .InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support
 .InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.
 annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc- 
   5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation
 .RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc- 
    5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.
  RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter
 .handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc- 
    5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc- 
    5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.46.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.46.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core- 
     9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core- 
    9.0.46.jar:9.0.46]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core- 
    9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core- 
   9.0.46.jar:9.0.46]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) ~[spring- 
   security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~ 
    [spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~ 
    [spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
     security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121) ~[spring- 
     security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) ~[spring- 
     security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
    security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.session.SessionManagementFilter.
    doFilter(SessionManagementFilter.java:126) ~ 
     [spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring- 
    security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
    security-web-5.5.0.jar:5.5.0]
at  
     org.springframework.security.web.authentication.

一个mousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) ~[spring-security-web-5.5.0.jar:5.5.0] 在 org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 安全-web-5.5.0.jar:5.5.0] 在 org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.d

    oFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[
   spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.savedrequest.R
   equestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
 ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
    security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.ui.
  DefaultLogoutPageGeneratingFilter.doFilterInternal(DefaultLogoutPageGeneratingFilter.java:58) ~[spring-security-web- 
 5.5.0.jar:5.5.0]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
     security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.ui.
  DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:237) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.ui
 .DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:223) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
  security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.
   doFilter(AbstractAuthenticationProcessingFilter.java:218) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.
   doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
    security-web-5.5.0.jar:5.5.0]
at org.springframework.security.oauth2.client.web.OAuth2Authorization
  RequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:178) ~[spring-security-oauth2-client- 
  5.5.0.jar:5.5.0]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
   security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security- 
 web-5.5.0.jar:5.5.0]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web- 
5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
   security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-
   security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-
   security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring- 
 security-web-5.5.0.jar:5.5.0]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
 doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.context.SecurityContextPersistenceFilter
 .doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.
  doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
  security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.
  doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring- 
 security-web-5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web- 
  5.5.0.jar:5.5.0]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) 
         ~[spring-security-web-5.5.0.jar:5.5.0]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) 
   ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) 
   ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
       ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
   ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
 ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 
      ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
   ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
   ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
       ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 
    ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) 
     ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 
   ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) 
     ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) 
 ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
      ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) 
     [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core- 
    9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core- 
     9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) [tomcat-embed-core- 
    9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.46.jar:9.0.46]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core- 
   9.0.46.jar:9.0.46]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

我已经检查过了,我得到了 accessToken 谢谢。

【问题讨论】:

【参考方案1】:

将 spring.neo4j.authentication 更改为 spring.core.Authentication

【讨论】:

以上是关于如何访问 oauth2 访问令牌和用户信息的主要内容,如果未能解决你的问题,请参考以下文章

如何在spring security oauth2授权服务器中通过jwt令牌获取用户信息?

Spring oauth2,使用访问令牌检索用户数据?

Keycloak 访问令牌与 UserInfo 令牌?

如何以管理员用户身份撤销用户的访问令牌和刷新令牌?在 Oauth2 中使用 JWT

Spring boot oauth2 - 访问令牌太长

OAuth2相关