gpt4 book ai didi

java - JWT 无法将访问 token 转换为 JSON

转载 作者:行者123 更新时间:2023-12-01 14:36:06 24 4
gpt4 key购买 nike

我知道有人问过这个问题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 key 的 JWT:

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

因为我的授权服务器与资源服务器在同一个地方,所以我将 .jks 和 public.txt(包含公钥)都添加到项目中。

token 已正确生成....这是一个示例:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ.mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp0s

但是,发送此 token 以从服务器获取任何资源时,出现以下错误:

{ “错误”:“无效 token ”, “error_description”:“无法将访问 token 转换为 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

我不知道为什么要否决这个问题。如果有任何我可以添加以增强问题的内容,请发表评论,我会尽力改进问题。

最佳答案

您最好将有关 keystore 的详细信息放入 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;
}

关于java - JWT 无法将访问 token 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com