[我正在尝试通过向我的Spring-boot后端提供API调用来对API调用进行身份验证,方法是为它提供我从Google获得的访问令牌。
据我对文档的了解,只需要声明就可以了
security.oauth2.resource.jwk.key-set-uri=https://www.googleapis.com/oauth2/v3/certs
在application.properties
文件中,以及启用资源服务器和Web安全性。
令牌正在表单的标题中发送
'Authorization': 'Bearer ya29.ImCQBz5-600zVNsB[...]ka-x5kC[...]hvw-BGf3m5Bck-HF[...]44'
[当我尝试进行身份验证时,出现以下控制台错误,出现401未经授权的错误:
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安全性库中的大部分功能,但是我已经尝试编写自己的简单bean来进行令牌管理。
@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());
}
}
我希望对令牌进行身份验证并能够显示信息。
我需要编写自己的函数来处理吗?
也许您必须实现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);
}
}