Throw custom exception from AuthenticationProvider to client(spring security)

411 views Asked by At

I develop a spring boot REST service. I use @ControllerAdvice for exception catching. Also, I have a custom AuthenticationProvider and check a license in it.

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    private final LicenseService licenseService;

    public MyAuthenticationProvider(LicenseService licenseService) {
        this.licenseService = licenseService;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //...some code
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
       try {
            //...some code
            licenseService.checkLicense(userDetails.getSomeId(), LicenseCode.FOO);
            //..some code
        } catch (LicenseException error) {
            throw new AccessDeniedException(error.getMessage());
        }
    }
  }

My licenseService throws LicenseException if the license does not exist or incorrect. I catch it and wrap to AccessDeniedException

at first, I wanted to catch LicenseException in @ControllerAdvice but quickly understood that it could be wrong. @ControllerAdvice catches exceptions in the controller layer.

That is why I wrap my exception to AccessDeniedException. But I want another logic: I want to throw a custom exception to the frontend. The frontend must understand this exception and show a special dialog to the client(License is required... bla-bla-bla). But I don't know how to do it on this step(AuthenticationProvider)

1

There are 1 answers

0
jan_tm On

Your Controller catching the exception from your AuthenticationProvider would send a ResponseEntity with HttpStatus.FORBIDDEN to your client. You can wrap your exception or an errormessage in the body of the HTTP response.