Reputation: 136
I want to customize the json response for BadCredential Exception (Error 401 Unauthorized) in Spring security.
Current json:
{
"timestamp": 1558062843375,
"status": 401,
"error": "Unauthorized",
"message": "Invalid credentials!",
"path": "/Test/api/v1/consultas/ddjj"
}
New format:
{
"codigo": "Invalid",
"mensaje": "Invalid credentials!"
}
I have tried by adding a Authentication Entry Point to my security config class but it didn't work. I'm only able to catch the 403 error but not the 401.
@Configuration
@Order(1)
public class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.antMatcher("/api/**")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
http.exceptionHandling().authenticationEntryPoint((request, response, e)
-> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
JSONObject respuesta = new JSONObject();
respuesta.put("codigo", "Invalid");
respuesta.put("mensaje", "Invalid credentials!");
response.getWriter().write(respuesta.toJSONString());
});
}
Upvotes: 0
Views: 1407
Reputation: 4891
AuthenticationException
class gives you access to exceptions related to Authentication. In my application, I created a RestResponseEntityExceptionHandler
class to handle all REST API exceptions and added a method to handle AuthenticationException class exceptions. You can customize the REST API response here. Please see the following implementation
RestResponseEntityExceptionHandler.java
import com.pj.springsecurity.exceptions.exceptions.GenericException;
import com.pj.springsecurity.model.exception.ErrorMessage;
import org.modelmapper.ModelMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
private final ModelMapper modelMapper;
public RestResponseEntityExceptionHandler(ModelMapper modelMapper)
{
this.modelMapper = modelMapper;
}
@ExceptionHandler({AuthenticationException.class})
public ResponseEntity<Object> handleAccessDeniedException(Exception exception, WebRequest webRequest)
{
return new ResponseEntity<>("Authentication Failed", new HttpHeaders(), HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(GenericException.class)
public ResponseEntity<ErrorMessage> handleGenericExceptions(GenericException genericException, WebRequest webRequest)
{
ErrorMessage errorMessage=modelMapper.map(genericException,ErrorMessage.class);
errorMessage.setStatusCode(errorMessage.getStatus().value());
return new ResponseEntity<>(errorMessage,errorMessage.getStatus());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorMessage> handleAllExceptions(Exception exception, WebRequest webRequest)
{
ErrorMessage errorMessage=modelMapper.map(exception,ErrorMessage.class);
return new ResponseEntity<>(errorMessage,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Please see this class for more details and let me know if you have any questions regarding this
Upvotes: 0