[英]Spring security return 401/403 instead of redirecting the user to the login page
[英]Spring security throw unauthorized instead of redirecting to login
我希望我的 spring web 應用程序將簡單地返回狀態代碼403 UNAUTHORIZED
UNAUTHORIZED 而不是重定向到/login
當用戶試圖訪問資源而沒有登錄或沒有正確的權限。
我目前使用oauth2
客戶端登錄設置了 spring 安全性,但我相信它與基本登錄也具有相同的行為。
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/allowed").permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login(this::configureOauthLogin) // sets up custom user services
.exceptionHandling()
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
});
}
我已經嘗試通過提供accessDeniedHandler
來處理它,但我沒有看到它改變任何東西,因為這個處理程序從未真正觸發過。
TLDR
使 spring 在未經授權的請求上拋出403
而不是302
。
編輯
這是我的過濾器鏈的轉儲
filters = {ArrayList@6668} size = 14
0 = {WebAsyncManagerIntegrationFilter@6635}
1 = {SecurityContextPersistenceFilter@6634}
2 = {HeaderWriterFilter@6633}
3 = {LogoutFilter@6632}
4 = {OAuth2AuthorizationRequestRedirectFilter@6631}
5 = {OAuth2LoginAuthenticationFilter@6630}
6 = {DefaultLoginPageGeneratingFilter@6629}
7 = {DefaultLogoutPageGeneratingFilter@6628}
8 = {RequestCacheAwareFilter@6627}
9 = {SecurityContextHolderAwareRequestFilter@6626}
10 = {AnonymousAuthenticationFilter@6625}
11 = {SessionManagementFilter@6624}
12 = {ExceptionTranslationFilter@6623}
13 = {FilterSecurityInterceptor@6622}
我想通了,原來這個控制流是由安全配置中的authenticationEntryPoint
處理的。 以下代碼提供了所需的行為:
http
.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.