gpt4 book ai didi

java - 使用 Spring Security 验证来自 Google 的访问 token

转载 作者:行者123 更新时间:2023-11-30 01:45:36 27 4
gpt4 key购买 nike

我正在尝试通过向 spring-boot 后端提供我从 Google 获得的访问 token 来验证 API 调用。

根据我对文档的理解,只需声明就足够了

security.oauth2.resource.jwk.key-set-uri=https://www.googleapis.com/oauth2/v3/certs

application.properties 文件中,同时启用资源服务器和 Web 安全性。

token 正在表单的 header 中发送

'Authorization': 'Bearer ya29.ImCQBz5-600zVNsB[...]ka-x5kC[...]hvw-BGf3m5Bck-HF[...]44'

当我尝试进行身份验证时,出现 401 Unauthorized 错误,并显示以下控制台错误:

OAuth2AuthenticationProcessingFilter: Authentication request failed: error="invalid_token", error_description="An I/O error occurred while reading the JWT: Invalid UTF-8 start byte 0xad at [Source: (byte[])"??"; line: 1, column: 3]

我希望尽可能地使用 Spring Security 库,但我尝试编写自己的简单 bean 来进行 token 管理。

@Configuration
@EnableResourceServer
@EnableWebSecurity
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasRole("USER");
}

@Bean
public TokenStore tokenStore() {
return new jwkTokenStore("https://www.googleapis.com/oauth2/v3/certs");
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
@Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServices());
}
}

我希望验证 token 并能够显示信息。

我需要编写自己的函数来处理这个问题吗?

最佳答案

也许您必须实现 WebSecurityConfigurerAdapter

@Configuration

@RequiredArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {

private final AADAppRoleStatelessAuthenticationFilter appRoleAuthFilter;

private final RestAuthenticationEntryPoint unauthorizedHandler;

private final RestAccessDeniedHandler accessDeniedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.authorizeRequests()
.antMatchers("/actuator/refresh").hasRole("Admin")
.antMatchers("/actuator/health").permitAll()
.anyRequest().fullyAuthenticated();

http.addFilterBefore(appRoleAuthFilter, UsernamePasswordAuthenticationFilter.class);

http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler)
.authenticationEntryPoint(unauthorizedHandler);

}
}

关于java - 使用 Spring Security 验证来自 Google 的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58131653/

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