当前位置: 首页 > 知识库问答 >
问题:

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

双志强
2023-03-14

我知道这里有人问过这个问题。然而,在这个问题上没有一行代码。我将分享我的代码,以便它可以帮助我和其他可能面临相同问题的人。

这里遵循代码...

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

因此,我使用以下命令创建了一个具有同化密钥的JWT:

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

由于我的授权服务器与资源服务器位于同一位置,因此我添加了两个。jks和公众。txt(包含公钥)输入到项目中。

已正确生成令牌。。。。以下是一个例子:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ. mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp

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

{“error”:“invalid_token”,“error_description”:“Cannot convert access token to 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个答案

汪弘毅
2023-03-14

您最好将密钥库的详细信息放入应用程序中。yml(或分别为应用程序属性)如下所示:

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

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    return converter;
}
 类似资料:
  • 我很难让Auth0以JWT格式返回访问令牌。我需要JWT格式的文件,以便使用javajwt库验证它们。 我正在使用Auth0登录,并使用获取访问令牌-我尝试将访问群体设置为我们的API标识符(在多个位置,包括lock auth参数和负载),但没有成功-返回访问令牌,但不是JWT。 或者,是否有用于验证“本机”Auth0访问令牌的Java库? 返回的代码用于POST到

  • 这是我的身份验证流程: 用户登录后收到两个令牌(具有过期时间的访问令牌和没有过期时间的刷新令牌) 对于每个用户,刷新令牌存储在数据库中名为refreshTokens的json列中(这是一个数组) 在客户端,访问令牌和刷新令牌都存储在本地存储器上 当需要验证用户时,如果访问令牌过期,将使用刷新令牌创建一个新的访问令牌,并将其发送回用户并保持用户登录 当用户注销时,数据库中存储的刷新令牌(在refre

  • 我在同意的情况下为我的应用程序手动/php sdk创建了docusignjwt访问令牌,并在restapi的代码中使用了该访问令牌。访问令牌的到期时间为1小时。如何在不征求同意的情况下一次又一次地更新DocuSign jwt访问令牌?或者如何延长访问令牌的到期时间?

  • 我正在使用以下示例来玩Spring Cloud OAuth2实现: https://github.com/spring-cloud-samples/authserver https://github.com/spring-cloud-samples/sso 第一个是OAuth服务器,它在对用户进行身份验证时生成JWT令牌。第二个是正在被消耗的资源。根据OAuth规范,资源将用户的身份验证转发给au

  • 我有一个ReactJS项目,当我登录时,我将我的令牌保存到本地存储。如何将令牌JWT转换为ab对象并获取id-user?

  • https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=your_app_client_id&response_type=code&redirect_uri=https%3a%2f%2flogin.microsoftonline.com%2fcommon%2foauth2%2fnativeclient&res