Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security anonymous 401 instead of 403

I have a problem with default behaviour in spring security with authorize requests provided with Java Config.

http        ....        .authorizeRequests()           .antMatchers("/api/test/secured/*").authenticated() 

When I do a call to for example /api/test/secured/user without login (with anonymous user), it returns 403 Forbidden. Is there an easy way to change status to 401 Unauthorized when anonymous user wants to get secured by authenticated() or @PreAuthorize resource?

like image 500
Mati Avatar asked Jun 04 '15 11:06

Mati


People also ask

How does Spring Security handle 403 Forbidden error?

Using Java, we can customize the 403 error handling process by using the accessDeniedPage() or accessDeniedHandler() methods while configuring the HttpSecurity element.

Is Anonymous () Spring Security?

Spring Security's anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API calls such as getCallerPrincipal , for example, will still return null even though there is actually an anonymous authentication object in the SecurityContextHolder .

Is WebSecurityConfigurerAdapter deprecated?

The type WebSecurityConfigurerAdapter is deprecatedWell, it's because the developers of Spring framework encourage users to move towards a component-based security configuration.

When should I use 401k vs 403?

401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials. 403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.


1 Answers

As of Spring Boot 2 class Http401AuthenticationEntryPoint has been removed (see Spring Boot Issue 10725).

Instead of Http401AuthenticationEntryPoint use HttpStatusEntryPoint with HttpStatus.UNAUTHORIZED:

http.exceptionHandling()     .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); 
like image 77
Tai Truong Avatar answered Sep 28 '22 11:09

Tai Truong