春季安全oauth2 JWT刷新令牌返回“身份验证失败:invalid_token无法将访问令牌转换为JSON”

时间:2018-12-17 20:20:16

标签: java jwt spring-security-oauth2 refresh-token

我已经使用JWT和初始身份验证实现了spring-security-oauth2,对资源的请求也正常工作,令牌增强器也是如此。当我尝试使用刷新令牌获取新的JWT时,出现错误"cannot convert access token to JSON"

public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    // ....
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter())
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService);
    }
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new CustomTokenEnhancer();
        converter.setSigningKey(jwtSigningKey);
        converter.setVerifierKey(jwtSigningKey);
        return converter;
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        Base64Utility base64 = new Base64Utility();
        clients.inMemory()
                .withClient(ApplicationConstants.CLIENT)
                .resourceIds(securityConstants.audience)
                .secret(...)
                .scopes(AuthorizationConstants.READ)
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(securityConstants.getAccessTokenValiditySeconds())
                .refreshTokenValiditySeconds(securityConstants.getRefreshTokenValiditySeconds());
    }
}

返回的access_token是普通的three.part.token,而refresh_token像这样:22cc0513-8a19-42bb-9bd4-631c6758a273

我使用此Javascript代码尝试刷新它:

function refreshToken() {
    var client = jwtForm.client.value;
    var clientSecret = getClientSecret();

    var data = "grant_type=refresh_token&refresh_token=" + jwt.refresh_token;

    var xhr = new XMLHttpRequest();
    xhr.open("POST", authServer + "/oauth/token");
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(client + ":" + atob(clientSecret)));
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4) {
            processResponse(xhr);
        }
    };
    xhr.send(data);
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

问题出在我的自定义JwtAccessTokenConverter中。如果您不打算创建自己的刷新令牌,则必须在增强方法中调用super.enchance。一旦我调用super.enhance,它就会创建一个JWT刷新令牌。