【发布时间】:2022-12-07 10:53:40
【问题描述】:
我还找不到解决问题的合适方法。我正在使用 Spring Security Oauth2 资源服务器来验证我的请求。这很好用。但是当用不同的场景进行测试时,发现如果没有授权标头存在,或者如果存在授权标头但值不是以承载.
Spring Boot Starter - 2.6.7
Spring Boot Starter Security - 2.6.7
Spring Security Config & Web - 5.6.3
Spring Security Core - 5.3.19
Spring Boot Starter OAuth2 Resource Server - 2.6.7
Spring OAuth2 Resource Server - 5.6.3
我指的是this answer并添加了以下代码BearerTokenAuthenticationEntryPoint.不同之处在于我使用的是内省 url 而不是 jwt。但这无济于事,那部分没有被执行。如果 Bearer 令牌存在,则只执行它。
我在这里错过了什么?
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class CustomResourceServerSecurityConfiguration {
@Value("${spring.security.oauth2.resourceserver.opaque-token.introspection-uri}")
String introspectionUri;
@Value("${spring.security.oauth2.resourceserver.opaque-token.client-id}")
String clientId;
@Value("${spring.security.oauth2.resourceserver.opaque-token.client-secret}")
String clientSecret;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaque -> opaque.introspectionUri(this.introspectionUri)
.introspectionClientCredentials(this.clientId, this.clientSecret))
.authenticationEntryPoint((request, response, exception) -> {
System.out.println("Authentication failed");
BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
delegate.commence(request, response, exception);
}))
.exceptionHandling(
(exceptions) -> exceptions.authenticationEntryPoint((request, response, exception) -> {
System.out.println("Authentication is required");
BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
delegate.commence(request, response, exception);
}));
return http.build();
}
}
【问题讨论】:
标签: java spring-security spring-security-oauth2 spring-oauth2