为Spring Rest API和认证定制错误对象。

问题描述 投票:0回答:1

我有一个spring boot rest API项目,我在思考如何改变spring boot返回的默认错误对象。

UseCase: token api要在没有认证的情况下被调用,其他apis要通过传递token来调用。swagger UI也需要用于同样的目的,错误响应需要被修改为自定义对象。

例如:Unauthorised api请求的默认结构是这样的。

{
    "timestamp": "2020-06-14T05:46:37.538+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/scholarship/api/v1.0/applicant" 
}

我希望它是这样的

{
  "status": "error",
  "message": "Unauthorised"
}

我也为项目配置了swagger ui,我的Config文件是这样的,可以帮助我打开swagger-ui.html,我也尝试过在异常处理程序中处理Unauthorised abject,但是没有成功。

我的Config文件是这样的,它可以帮助我打开swagger-ui.html,我也试着在异常处理程序中获取一个Unauthorised abject的句柄,但它没有启动。

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


    private static final RequestMatcher PROTECTED_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher("/api/**")
    );

    AuthenticationProvider provider;

    public SecurityConfig(final AuthenticationProvider authenticationProvider) {
        super();
        this.provider = authenticationProvider;
    }

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(provider);
    }

    @Override
    public void configure(final WebSecurity webSecurity) {
        webSecurity.ignoring().antMatchers("/token/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
                .and()
                .authenticationProvider(provider)
                .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(PROTECTED_URLS)
                .authenticated()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();
    }

    @Bean
    AuthenticationFilter authenticationFilter() throws Exception {
        log.error("in authenticationFilter");
        final AuthenticationFilter filter = new AuthenticationFilter(PROTECTED_URLS);
        filter.setAuthenticationManager(authenticationManager());

        //filter.setAuthenticationSuccessHandler(successHandler());
        return filter;
    }


    @Autowired
    private HandlerExceptionResolver handlerExceptionResolver;

    public AuthenticationEntryPoint authenticationEntryPoint() {
        log.error("in authenticationEntryPoint");
        return new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response,
                                 AuthenticationException authException) throws IOException, ServletException {
                log.error("in commence");
                try {
                    log.error(authException.getLocalizedMessage());
                    handlerExceptionResolver.resolveException(request, response, null, authException);
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    throw new ServletException(e);
                }
            }
        };
    }
}

另外,我有一个@ControllerAdvice来重新格式化错误对象,但也没有用。

@ExceptionHandler(value = {InsufficientAuthenticationException.class})
    public final ResponseEntity<Object> authenticationException(InsufficientAuthenticationException ex) {
        List<String> details = new ArrayList<>();
        details.add("Authentication is required to access this resource");
        ErrorResponse error = new ErrorResponse("error", "Unauthorized", details);
        return new ResponseEntity(error, HttpStatus.FORBIDDEN);
    }

可能是什么配置错误?

更新1.如果我改成这样,那么在调用安全API时,我得到了我的自定义对象,但是swagger Ui却打不开,而且我的swagger UI访问也出现了自定义错误。

如果我改成这样,那么当调用安全API时,我得到了我的自定义对象,但是swagger Ui没有打开,我得到了我的自定义错误,用于访问swagger UI。

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

        http.authorizeRequests()
                .anyRequest()
                .fullyAuthenticated();

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint());
    }

访问Swagger用户界面时出错

{"status":"error","message":"Unauthorized","errors":["Authentication is required to access this resource"]}

更新2:

改成下面的样子,打开Swagger UI,但错误对象又不是自定义的,那么。

 @Override
    public void configure(HttpSecurity http) throws Exception {
        log.error("in configure");
        http.authenticationProvider(provider)
                .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(PROTECTED_URLS)
                .fullyAuthenticated();

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint());
    }

更新3.核心问题在configure(HttpSecurity http)方法。

核心问题在configure(HttpSecurity http)方法上。

如果我添加以下两行,API的认证,但错误对象是默认对象。如果我删除这两行,API没有被认证(即使你传递令牌,他们也一直失败),但我得到了自定义的错误对象。

.authenticationProvider(provider)
                .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
spring-boot swagger-ui swagger-2.0
1个回答
1
投票

来自Servlet Filter的异常,如果没有到达控制器,则由以下方法处理 BasicErrorController.

你需要覆盖 BasicErrorController 来改变spring抛出的默认异常体。

如何覆盖。

@RestController
@Slf4j
public class BasicErrorControllerOverride extends AbstractErrorController {

  public BasicErrorControllerOverride(ErrorAttributes errorAttributes) {
    super(errorAttributes);
  }

  @RequestMapping
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    HttpStatus status = this.getStatus(request);

    /*
       If you want to pull default error attributes and modify them, use this
       Map<String, Object> defaultErrorAttributes = this.getErrorAttributes(request, false);
    */

    Map<String, Object> errorCustomAttribute = new HashMap<>();
    errorCustomAttribute.put("status", "error");
    errorCustomAttribute.put("message", status.name());
    return new ResponseEntity(errorCustomAttribute, status);
  }

  @Override
  public String getErrorPath() {
    return "/error";
  }
}

错误响应是怎样的

{
    "message": "UNAUTHORIZED",
    "status": "error"
}
© www.soinside.com 2019 - 2024. All rights reserved.