简体   繁体   English

Spring boot:如何自定义禁止的错误json

[英]Spring boot : How could I customize the forbidden error json

I was wondering if I could customize the following forbidden JSON error:我想知道是否可以自定义以下禁止的 JSON 错误:

Actual Response实际反应

{
  "timestamp": "2018-09-26T06:11:05.047+0000",
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied",
  "path": "/api/rest/hello/me"
}

Custom Response - I get it when the user request does not have permissions.自定义响应 - 当用户请求没有权限时我得到它。

{ 
  "code": 403,
  "message": "Access denied by the system",
  "status": "Failure"
}

My Web security class我的网络安全课

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private JwtTokenProvider jwtTokenProvider;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.authorizeRequests()//
        .antMatchers("/rest/hello/signin").permitAll()//
        .anyRequest().authenticated();
    http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
  }
}

You can create custom handler using the Jackson ObjectMapper like this:您可以使用Jackson ObjectMapper创建自定义处理程序,如下所示:

@Bean
public AccessDeniedHandler accessDeniedHandler() {
    return (request, response, ex) -> {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        ServletOutputStream out = response.getOutputStream();
        new ObjectMapper().writeValue(out, new MyCustomErrorDTO());
        out.flush();
    };
}

And configure your HttpSecurity like this:并像这样配置你的HttpSecurity

http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

Also, you can try throw AuthenticationException :此外,您可以尝试抛出AuthenticationException

@Bean
public AuthenticationFailureHandler failureHandler() {
    return (request, response, ex) -> { throw ex; };
}

And handle them in @RestControllerAdvice :并在@RestControllerAdvice处理它们:

@RestControllerAdvice
public class AdviseController {

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public MyCustomErrorDTO handleAuthenticationException(AuthenticationException ex) {
        return new MyCustomErrorDTO();
    }
}

But I'm not sure that it will work, you can check it out.但我不确定它会起作用,你可以检查一下。

To display custom message i created entry point class JwtAuthenticationEntryPoint for JWT Security.为了显示自定义消息,我为 JWT Security 创建了入口点类 JwtAuthenticationEntryPoint。

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            AuthenticationException e) throws IOException, ServletException {
        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Sorry, You're not authorized to access this resource.");
    }
}

And pass as entry point To security config like,并作为入口点传递到安全配置,例如,

 @Configuration
 @EnableWebSecurity
 @EnableGlobalMethodSecurity(prePostEnabled = true)
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private JwtAuthenticationEntryPoint unauthorizedHandler;

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
                    .antMatchers("auth/singIn" , "auth/singUp/")
                    .permitAll().anyRequest().authenticated();
    }
}

Or you can use @ControllerAdvice and custom exception handling to handle custom or system exception或者您可以使用@ControllerAdvice 和自定义异常处理来处理自定义或系统异常

add this in your controller or ExceptionHandler :在您的控制器或 ExceptionHandler 中添加:

    @ExceptionHandler(AccessDeniedException.class)
    public @ResponseBody ResponseEntity<AuthzErrorResponse> handlerAccessDeniedException(final Exception ex,
            final HttpServletRequest request, final HttpServletResponse response) {

        AuthzErrorResponse authzErrorResponse = new AuthzErrorResponse();
        authzErrorResponse.setMessage("Access denied");

        return new ResponseEntity<>(authzErrorResponse, HttpStatus.FORBIDDEN);
    }

Note:AuthzErrorResponse is my custom POJO which I want to return.注意:AuthzErrorResponse 是我想要返回的自定义 POJO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM