EchoCow
EchoCow

Reputation: 173

@PreAuthorize isAnonymous doesn't work on Spring Boot

@PreAuthorize with isAnonymous() does not seem to work with Spring (actually, Spring Boot).

Here is my code:

@RestController
@RequiredArgsConstructor
public class ValidateCodeController {

    private final @NonNull ValidateCodeProcessorHolder validateCodeProcessorHolder;

//  @PreAuthorize("permitAll()")
    @PreAuthorize("isAnonymous()")
    @GetMapping(SecurityConstants.VALIDATE_CODE_URL_PREFIX + "/{type}")
    public void creatCode(HttpServletRequest request, HttpServletResponse response,
                          @PathVariable String type) throws Exception {
        validateCodeProcessorHolder.findValidateCodeProcessor(type)
                .create(new ServletWebRequest(request, response));
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/test")
    public HttpEntity<?> resource() {
        return ResponseEntity.ok(123);
    }

}

But I get an HTTP 403 Forbidden response:

{
    "timestamp": "2019-08-02T08:36:50.859+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/code/email"
}

and /test

{
    "timestamp": "2019-08-02T08:36:48.202+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/test"
}

In my configurer file.

@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
//              If use this, it can work.
//                .antMatchers("/code/*").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

I expect get the resource.

Upvotes: 2

Views: 1970

Answers (3)

Romil Patel
Romil Patel

Reputation: 13757

We can not use isAnonymous(), permitAll() with @PreAuthorize. These can be used in configure(HttpSecurity http)

The correct way is to use ROLE_NAME

@PreAuthorize("hasRole('ADMIN')")
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")

We can also achieve this in configure(HttpSecurity http) as below

     http
     .csrf().disable()
     .authorizeRequests()
     .antMatchers("/login","/logout").permitAll() 
     .antMatchers("/admin/**").hasRole("ADMIN") 
     .antMatchers(HttpMethod.GET,"/user/**").hasAnyRole("ADMIN","USER")
     .antMatchers(HttpMethod.POST,"/user/**").hasAnyRole("ADMIN","USER")
     .anyRequest().authenticated();

Upvotes: 2

In your WebSecurityConfig class you have the following definition:

...
.anyRequest()
.authenticated()
...

You are saying to Spring que all request must be authenticated. Then, your annotation @PreAuthorize("isAnonymous()") always will be false and return a 403 http code.

Visit the following link to see more information: https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

Upvotes: 1

Charles Lee
Charles Lee

Reputation: 371

use

@PreAuthorize("hasRole('ADMIN')")

or

@PreAuthorize("hasAuthority('ROLE_ADMIN')")

Refer to https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-faq-role-prefix

Upvotes: 0

Related Questions