invalid_token: невозможно преобразовать токен доступа в JSON - PullRequest
1 голос
/ 25 апреля 2019

Я получаю ошибку при обновлении токена (grant_type = refresh_token). Похоже, что пользователь долгое время не использовал приложение, и истек срок действия как маркера доступа, так и токена обновления. Когда приложение теперь пытается обновить токен, оно получает ошибку

{
"error": "invalid_token",
"error_description": "Cannot convert access token to JSON" 
  }

Я видел много сообщений по этой проблеме, но я все еще сталкиваюсь с этой ошибкой. Я пытался использовать setVerifierKey. Но не повезло. Вот код:

@Configuration
   @EnableWebSecurity
   @EnableGlobalMethodSecurity(prePostEnabled = true)
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${security.signing-key}")
private String signingKey;

@Value("${security.encoding-strength}")
private Integer encodingStrength;

@Value("${security.security-realm}")
private String securityRealm;

@Autowired
private UserDetailsService userDetailsService;

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
          //  .passwordEncoder(new ShaPasswordEncoder(encodingStrength));
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .httpBasic()
            .realmName(securityRealm)
            .and()
            .csrf()
            .disable();

}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey(signingKey);
    return converter;
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
@Primary //Making this primary to avoid any accidental duplication with another token service instance of the same name
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    return defaultTokenServices;
}
}



//AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value("${security.jwt.client-id}")
private String clientId;

@Value("${security.jwt.client-secret}")
private String clientSecret;

@Value("${security.jwt.grant-type}")
private String grantType;

@Value("${security.jwt.scope-read}")
private String scopeRead;

@Value("${security.jwt.scope-write}")
private String scopeWrite = "write";

@Value("${security.jwt.resource-ids}")
private String resourceIds;

@Autowired
private TokenStore tokenStore;

@Autowired
private JwtAccessTokenConverter accessTokenConverter;

@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
    configurer
            .inMemory()
            .withClient(clientId)
            .secret(clientSecret)
            .authorizedGrantTypes("client_credentials", "password", "refresh_token", "authorization_code")
            .scopes(scopeRead, scopeWrite)
           // .accessTokenValiditySeconds(60)
           // .refreshTokenValiditySeconds(2000)
            .resourceIds(resourceIds);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
    endpoints.tokenStore(tokenStore)
            .accessTokenConverter(accessTokenConverter)
            .tokenEnhancer(enhancerChain).userDetailsService(userDetailsService)
            .authenticationManager(authenticationManager);
}

}

Я ожидаю, что токен будет обновлен, но я получаю ошибку, как указано выше. мои свойства конфигурации:

  • security.oauth2.resource.filter-order = 3
  • security.signing-key = ZMaasazkSjmaasw
  • security.encoding-strong = 256
  • security.security-realm = Spring Boot Пример JWT Realm
  • security.jwt.grant-type = пароль security.jwt.scope-read = read
  • security.jwt.scope-write = write
  • security.jwt.resource-ида = testjwtresourceid

Любая помощь приветствуется !!

...