如何从springboot中的未经授权的响应中删除变量 [英] How to remove a variable from Unauthorized response in springboot

查看:13
本文介绍了如何从springboot中的未经授权的响应中删除变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查用户未授权时,我有这个回应.

I have this response when it comes to check the user Unauthorized.

我有可能从未经授权的响应中删除路径吗?因为它没有为用户提供有价值的信息

i there any possibility to remove the Path from the Unauthorized response ? since it does not gives valuable information for the user

{
"timestamp": "2021-03-18T09:16:09.699+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/test/v1/api/test.com/config/settings"

}

这是我的配置的样子

public class ResourceConfig extends ResourceServerConfigurerAdapter {


@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        .cors();

    httpSecurity
        .anonymous().disable()
        .requestMatchers().antMatchers("/api/**")
        .and()
        .authorizeRequests()
        .antMatchers("/api/**")
        .authenticated()
        .and()
        .exceptionHandling()
        .accessDeniedHandler(new OAuth2AccessDeniedHandler());

}

推荐答案

添加使用自定义 AuthenricationEntryPoint 的 @linhx 想法,您可以使用 HandlerExceptionResolver 解析为 <强>页面.

Adding on @linhx idea of using custom AuthenricationEntryPoint, you can use HandlerExceptionResolver which resolves to a page.

您可以在此处获得不同方法的详细比较.

@Component
public class ABAuthenticationEntryPoint implements AuthenticationEntryPoint {

    protected final Logger logger = LoggerFactory.getLogger(ABAuthenticationEntryPoint.class);

    private final String realmName = "CustomRealm";

     @Autowired
     @Qualifier("handlerExceptionResolver")
     private HandlerExceptionResolver resolver;
     
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        resolver.resolveException(request, response, null, authException);
    }
}

HandlerExceptionResolver 使用处理程序 (HandlerMethod) 获取 Controller 类并扫描它以查找带有 @ExceptionHandler 注释的方法.如果此方法之一与异常 (ex) 匹配,则调用此方法以处理异常.(否则返回 null 表示此异常解析器不负责).

The HandlerExceptionResolver uses the handler (HandlerMethod) to obtain the Controller class and scan it for methods annotated with @ExceptionHandler. If one of this methods matches the exception (ex) then this methods get invoked in order to handle the exception. (else null get returned signaling that this exception resolver feels no responsible).

所以,添加一个带有 @ControllerAdvice 的类:

So, add a class with @ControllerAdvice:

@ExceptionHandler(value = InsufficientAuthenticationException.class)
public ResponseEntity<Object> handleInsufficientAuthenticationException(InsufficientAuthenticationException ex) {
    String methodName = "handleInsufficientAuthenticationException()";
    return buildResponseEntity(HttpStatus.UNAUTHORIZED, null, null, ex.getMessage(), null);
}

private ResponseEntity<Object> buildResponseEntity(HttpStatus status, HttpHeaders headers, Integer internalCode, String message, List<Object> errors) {
        ResponseBase response = new ResponseBase()
                .success(false)
                .message(message)
                .resultCode(internalCode != null ? internalCode : status.value())
                .errors(errors != null
                        ? errors.stream().filter(Objects::nonNull).map(Objects::toString).collect(Collectors.toList())
                        : null);
        
        return new ResponseEntity<>((Object) response, headers, status);
    }

SecurityConfig 类:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
    
    @Autowired
    private ABAuthenticationEntryPoint authenticationEntryPoint;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
        .....
        .and()
        .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); //AuthenticationEntryPoint has to be the last
    }
}

最后你会得到如下内容,基于你如何buildResponseEntity

Finally you will get something like the following, based on how you buildResponseEntity

{
    "success": false,
    "resultCode": 401,
    "message": "Full authentication is required to access this resource"
}

这篇关于如何从springboot中的未经授权的响应中删除变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆