如何在 Spring Boot 中从未经授权的响应中删除变量

2024-01-23

当涉及到检查用户未经授权时,我有这样的响应。

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

{
"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());

}

添加 @linhx 使用自定义的想法AuthenricationEntryPoint, 您可以使用HandlerExceptionResolver这解析为page.

您可以获得不同方法的详细比较here https://www.baeldung.com/exception-handling-for-rest-with-spring.

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

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

所以,添加一个类@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 class:

@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

{
    "success": false,
    "resultCode": 401,
    "message": "Full authentication is required to access this resource"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring Boot 中从未经授权的响应中删除变量 的相关文章

随机推荐