0

i have written a custom Expression root for my @PreAuthorize annotations . The logic itself works fine. However the application returns a 403, but i need to return a 401.

public class JwtConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new OwnTokenFilter(), UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(new HttpStatusEntryPoint(UNAUTHORIZED));
    }
}

The OwnTokenFilter extracts a jwt token and provides it to the SecurityContext. My expectation was, that if the authorization fails, an UNAUTHORIZED was returned, but it is simply ignored. I am using Spring Boot 2.1.x

My expression root looks like

public class ExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {...

    public boolean hasRoleOneOf(final String ... expectedRoles) {
       ...
        return roleMatched? true : false;
    }

Thank you

Neophyn33
  • 21
  • 3
  • 1
    Side note: `401 Unauthorized`, despite its name, is an **authentication** error, so a REST services should return 401 when *authentication* fails and throw 403 when *authorization* fails. https://stackoverflow.com/a/6937030/1759845 – BackSlash Oct 09 '19 at 14:03

1 Answers1

0

Found a solution

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import static org.springframework.http.HttpStatus.UNAUTHORIZED;

@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public ResponseEntity<String> handleControllerException(AccessDeniedException ex) {
      return new ResponseEntity<>(ex.getMessage(), UNAUTHORIZED);
    }

}

Not sure if it is the best one :)

Neophyn33
  • 21
  • 3