我有一个 Spring MVC jsf 应用程序。每个页面/端点请求都通过
customAuthorizationManager
进行保护。
我正在尝试将任何未经身份验证/未经授权的请求重定向到我们的 OAuth2 服务器的登录页面 (https://xxx/op/v1/auth)。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
.....
@Bean
@Order(1)
public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests.anyRequest().access(customAuthorizationManager)
)
// Redirect to the OAuth 2.0 Login endpoint when not authenticated from the authorization endpoint
.exceptionHandling(exceptions -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("https://xxx/op/v1/auth"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
);
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain filterChain2(HttpSecurity http) throws Exception {
http
// OAuth2 Login handles the redirect to the OAuth 2.0 Login endpoint from the authorization server filter chain above
.oauth2Login(Customizer.withDefaults())
.oauth2Client(c -> this.customClientRegistration());
return http.build();
}
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.customClientRegistration());
}
private ClientRegistration customClientRegistration() {
return ClientRegistration
.withRegistrationId("my-combined-client")
.clientId("4d06125e-xxx")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("https://xxx")
.authorizationUri("https://xxx/op/v1/auth")
.tokenUri("https://xxx/op/v1/token")
.userInfoUri("https://xxx/op/v1/userinfo")
.jwkSetUri("https://xxx/op/v1/keys")
.build();
}
}
我看到未经授权的请求被拒绝并重定向到登录页面,但没有使用customClientRegistration
(
4d06125e-xxx)中定义的正确client-id
那么,您能帮我将这些未经身份验证/未经授权的请求重定向到外部 OAuth 登录页面吗?
更新1
我删除了第二个过滤器并将其内容附加到第一个过滤器中,但结果是相同的:
@Bean
@Order(1)
public SecurityFilterChain filter1(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests.anyRequest().access(customAuthorizationManager)
)
// Redirect to the OAuth 2.0 Login endpoint when not authenticated from the authorization endpoint
.exceptionHandling(exceptions -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("https://xxx/op/v1/auth"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
)
.oauth2Login(Customizer.withDefaults())
.oauth2Client(c -> this.customClientRegistration());
return http.build();
}
/*@Bean
@Order(2)
public SecurityFilterChain filter2(HttpSecurity http) throws Exception {
http
// OAuth2 Login handles the redirect to the OAuth 2.0 Login endpoint from the authorization server filter chain above
.oauth2Login(Customizer.withDefaults())
.oauth2Client(c -> this.customClientRegistration());
return http.build();
}*/
删除你的
exceptionHandling
。
授权代码流中的第一个请求是向 OAuth2 客户端发送请求,要求其设置会话、随机数、状态等。OAuth2 客户端会将使用重定向到授权服务器“授权”端点,并等待他返回授权码。