如何在springboot中从未授权响应中删除变量



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

是否有可能从未经授权的响应中删除Path?因为它不会为用户提供有价值的信息

{
"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

你可以在这里得到不同方法的详细比较。

@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 get,表示此异常解析程序认为没有责任(。

因此,添加一个具有@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

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

最新更新