首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在springboot中从未经授权的响应中删除变量

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

Stack Overflow用户
提问于 2021-03-18 09:21:58
回答 1查看 748关注 0票数 3

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

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

代码语言:javascript
运行
复制
{
"timestamp": "2021-03-18T09:16:09.699+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/test/v1/api/test.com/config/settings"

}

我的配置就是这样的

代码语言:javascript
运行
复制
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());

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-18 10:12:12

添加使用自定义AuthenricationEntryPoint的@linhx概念,您可以使用解析为页面HandlerExceptionResolver

您可以获得不同方法的详细比较这里

代码语言:javascript
运行
复制
@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,表示此异常解析器感到不负责)。

所以,使用@ControllerAdvice添加一个类

代码语言:javascript
运行
复制
@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类:

代码语言:javascript
运行
复制
@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

代码语言:javascript
运行
复制
{
    "success": false,
    "resultCode": 401,
    "message": "Full authentication is required to access this resource"
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66688115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档