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
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:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.