【问题标题】:How to customize json response for BadCredentials Exception in Spring Security?如何在 Spring Security 中自定义 BadCredentials 异常的 json 响应?
【发布时间】:2019-05-17 13:10:14
【问题描述】:

我想在 Spring security 中自定义 BadCredential Exception (Error 401 Unauthorized) 的 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());
            });
        }

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    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了解更多详情,如果您对此有任何疑问,请告诉我

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      相关资源
      最近更新 更多