Home > database >  401 on .permitAll() request in Spring Security
401 on .permitAll() request in Spring Security

Time:09-16

I have specified .permitAll() on the endpoint "/api/v2/user/login/**" but it still gives 401 when I don't give any authentication details in postman.

In fact, it's showing abnormal behaviour, below are my observations.

  1. Gives 200 for any correct user details (regardless of role).
  2. If I make a request with correct user details, it gives 200. If just after that request I do another request with incorrect password, it still gives 200. But incorrect username isn't tolerated.
  3. Once it gives 401, it will keep giving 401 for all requests until I enter correct credentials.

CSRF is disabled so that shouldn't be an issue. I have tried playing with the order of permitAll request but that hasn't worked yet. Checkout the last antMatchers.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().
    authorizeRequests().        
    antMatchers(HttpMethod.POST, "/api/v2/user/", "/api/v2/user", "/api/v2/user/change-role/**").hasAuthority("ROOT").
    antMatchers(HttpMethod.GET, "/api/v2/user/", "/api/v2/user").hasAuthority("ROOT").
    antMatchers(HttpMethod.POST, "/api/v1/customers/", "/api/v1/customers").hasAnyAuthority("ADMIN", "ROOT").
    antMatchers(HttpMethod.GET, "/api/v1/customers/", "/api/v1/customers").hasAnyAuthority("EMPLOYEE", "ADMIN", "ROOT").
    antMatchers(HttpMethod.POST, "/api/v2/user/login/**").permitAll().
    anyRequest().
    authenticated().
    and().
    httpBasic();
}

And here's the relevant controller method.

@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<Boolean> loginUser(@RequestParam String username, @RequestParam String password){
    return myUsersService.loginUser(username, password);
}

Any ideas are appreciated. Thanks!

CodePudding user response:

Put antMatchers with permitAll first in the chain and remove /** to match the actual path you want to permit without auth.

  • Related