简体   繁体   English

JWT无法将访问令牌转换为JSON

[英]JWT Cannot convert access token to JSON

I know this question has been asked here . 我知道这里已经问这个问题。 However, there is not 1 line of code on the question. 但是,问题上没有1行代码。 I will share my code so it may help me and others that could face the same issue. 我将共享我的代码,以便对我和其他可能遇到相同问题的人有所帮助。

Here follows the code... 下面是代码...

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
@Qualifier(value = "authenticationManager")
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.allowFormAuthenticationForClients().passwordEncoder(passwordEncoder);
}

/*
 * Não remover, Configura os Endpoints para o oAuth2
 */
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
    endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()).tokenEnhancer(tokenEnhancer())
            .userDetailsService(userDetailsService);
}

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"),
            "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    return converter;
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    defaultTokenServices.setReuseRefreshToken(false);
    return defaultTokenServices;
}

} }

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

@Override
@Bean(name = "authenticationManager")
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}

@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
    return new JwtAuthenticationTokenFilter();
}

@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()


            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            // .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

            // allow anonymous resource requests
            .antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js")
            .permitAll().antMatchers("/auth/**").permitAll().anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity.headers().cacheControl();
    // @formatter:on
}

} }

@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().anyRequest().authenticated();
}

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = org.apache.commons.io.IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}


@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    defaultTokenServices.setReuseRefreshToken(false);
    return defaultTokenServices;
}

So I have created a JWT with assimetric key, using the following command: 因此,我使用以下命令创建了带有辅助密钥的JWT:

keytool -genkeypair -alias mytest -keyalg RSA -keypass mypass -keystore mytest.jks -storepass mypass keytool -genkeypair -alias mytest -keyalg RSA -keypass mypass -keystore mytest.jks -storepass mypass

Since my authorization server is in the same place as the resource server, I added both the .jks and also the public.txt (that contains the public key) into the project. 由于授权服务器与资源服务器位于同一位置,因此我将.jks和public.txt(包含公共密钥)添加到了项目中。

The token gets generated correctly.... Here is an example: 令牌已正确生成。...这是一个示例:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ.mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp0s eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ.mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp0s

However, sending this token to get any resource from the server, I got the following error: 但是,发送此令牌以从服务器获取任何资源时,出现以下错误:

{ "error": "invalid_token", "error_description": "Cannot convert access token to JSON" } {“ error”:“ invalid_token”,“ error_description”:“无法将访问令牌转换为JSON”}

So, what is missing? 那么,缺少了什么呢?

EDIT 编辑

The server logs: 服务器日志:

> Caused by: java.security.SignatureException: Signature length not correct: 
got 32 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189)
at java.security.Signature$Delegate.engineVerify(Signature.java:1219)
at java.security.Signature.verify(Signature.java:652)
at org.springframework.security.jwt.crypto.sign.RsaVerifier.verify(RsaVerifier.java:54)
... 57 more

EDIT 2 编辑2

I have no ideia why downvoted the question. 我不认为为什么不赞成这个问题。 If there is anything I could add to enhance the question, please leave a comment and I'll do my best to improve the question. 如果有什么我可以添加来完善这个问题的,请发表评论,我会尽力改善这个问题。

You could better put details about the keystore into the application.yml (or application.properties respectively) as follows: 您最好将有关密钥库的详细信息放入application.yml (或分别为application.properties )中,如下所示:

encrypt:
  key-store:
    location: mytest.jks
    alias: mytest
    password: mypass
    secret: mypass

Then you could simplify your code in both OAuth2Config and ResourceServer : 然后,您可以在OAuth2ConfigResourceServer简化代码:

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    return converter;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM