如何在Spring Security中为BadCredentials异常自定义json响应?

时间:2019-05-17 03:24:00

标签: spring-boot spring-security

我想为Spring安全性中的BadCredential异常(错误401未经授权)定制json响应。

当前json:

{
    "timestamp": 1558062843375,
    "status": 401,
    "error": "Unauthorized",
    "message": "Invalid credentials!",
    "path": "/Test/api/v1/consultas/ddjj"
}

新格式:

{
    "codigo": "Invalid",
    "mensaje": "Invalid credentials!"
}

我尝试通过将身份验证入口点添加到我的安全性配置类来尝试,但是它不起作用。我只能捕获403错误,但不能捕获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());
            });
        }

1 个答案:

答案 0 :(得分:0)

AuthenticationException类可让您访问与身份验证相关的异常。在我的应用程序中,我创建了一个RestResponseEntityExceptionHandler类来处理所有REST API异常,并添加了一种方法来处理AuthenticationException类异常。您可以在此处自定义REST API响应。请参阅以下实现

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);
    }
}

有关更多详细信息,请参见this class,如果对此有任何疑问,请告诉我