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

时间:2017-12-07 17:49:56

标签: java spring-security

我知道这个问题已被问到here。但是,问题上没有一行代码。我将分享我的代码,以便它可以帮助我和其他可能面临同样问题的人。

以下是代码......

@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;
}

所以我使用以下命令创建了一个带有assimetric键的JWT:

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

由于我的授权服务器与资源服务器位于同一位置,因此我将.jks和public.txt(包含公钥)添加到项目中。

令牌生成正确....这是一个例子:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ.mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp0s

但是,发送此令牌以从服务器获取任何资源,我收到以下错误:

{     "错误":" invalid_token",     " error_description":"无法将访问令牌转换为JSON" }

那么,缺少什么?

修改

服务器记录:

> 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

编辑2

我没有想到为什么要对这个问题进行投票。如果我可以添加任何内容来增强问题,请发表评论,我会尽力改进这个问题。

1 个答案:

答案 0 :(得分:0)

您最好将有关密钥库的详细信息放入application.yml(或application.properties),如下所示:

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

然后,您可以在OAuth2ConfigResourceServer中简化代码:

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