gpt4 book ai didi

java - 处理 Spring Boot 资源服务器中的安全异常

转载 作者:IT老高 更新时间:2023-10-28 13:53:25 26 4
gpt4 key购买 nike

如何让我的自定义 ResponseEntityExceptionHandlerOAuth2ExceptionRenderer 在纯资源服务器上处理 Spring 安全性引发的异常?

我们实现了一个

@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

所以每当资源服务器上出现错误时,我们希望它回答

{
"message": "...",
"type": "...",
"status": 400
}

资源服务器使用 application.properties 设置:

security.oauth2.resource.userInfoUri: http://localhost:9999/auth/user

对我们的身份验证服务器的请求进行身份验证和授权。

然而,任何 spring 安全错误都会绕过我们的异常处理程序

    @ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<Map<String, Object>> handleInvalidTokenException(InvalidTokenException e) {
return createErrorResponseAndLog(e, 401);
}

并产生任一

{
"timestamp": "2016-12-14T10:40:34.122Z",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/templates/585004226f793042a094d3a9/schema"
}

{
"error": "invalid_token",
"error_description": "5d7e4ab5-4a88-4571-b4a4-042bce0a076b"
}

那么如何配置资源服务器的安全异常处理呢?我所找到的只是关于如何通过实现自定义 OAuth2ExceptionRenderer 来自定义身份验证服务器的示例。但我找不到将它连接到资源服务器安全链的位置。

我们唯一的配置/设置是这样的:

@SpringBootApplication
@Configuration
@ComponentScan(basePackages = {"our.packages"})
@EnableAutoConfiguration
@EnableResourceServer

最佳答案

如前面的评论中所述,请求在到达 MVC 层之前被安全框架拒绝,因此 @ControllerAdvice 在这里不是一个选项。

Spring Security 框架中有 3 个接口(interface)可能在这里感兴趣:

  • org.springframework.security.web.authentication.AuthenticationSuccessHandler
  • org.springframework.security.web.authentication.AuthenticationFailureHandler
  • org.springframework.security.web.access.AccessDeniedHandler

您可以创建每个接口(interface)的实现,以自定义为各种事件发送的响应:登录成功、登录失败、尝试访问权限不足的 protected 资源。

以下将在登录尝试失败时返回 JSON 响应:

@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler
{
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException, ServletException
{
response.setStatus(HttpStatus.FORBIDDEN.value());

Map<String, Object> data = new HashMap<>();
data.put("timestamp", new Date());
data.put("status",HttpStatus.FORBIDDEN.value());
data.put("message", "Access Denied");
data.put("path", request.getRequestURL().toString());

OutputStream out = response.getOutputStream();
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, data);
out.flush();
}
}

您还需要向安全框架注册您的实现。在 Java 配置中,如下所示:

@Configuration
@EnableWebSecurity
@ComponentScan("...")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
@Override
public void configure(HttpSecurity http) throws Exception
{
http
.addFilterBefore(corsFilter(), ChannelProcessingFilter.class)
.logout()
.deleteCookies("JESSIONID")
.logoutUrl("/api/logout")
.logoutSuccessHandler(logoutSuccessHandler())
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/api/login")
.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler())
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint())
.accessDeniedHandler(accessDeniedHandler());
}

/**
* @return Custom {@link AuthenticationFailureHandler} to send suitable response to REST clients in the event of a
* failed authentication attempt.
*/
@Bean
public AuthenticationFailureHandler authenticationFailureHandler()
{
return new RestAuthenticationFailureHandler();
}

/**
* @return Custom {@link AuthenticationSuccessHandler} to send suitable response to REST clients in the event of a
* successful authentication attempt.
*/
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler()
{
return new RestAuthenticationSuccessHandler();
}

/**
* @return Custom {@link AccessDeniedHandler} to send suitable response to REST clients in the event of an attempt to
* access resources to which the user has insufficient privileges.
*/
@Bean
public AccessDeniedHandler accessDeniedHandler()
{
return new RestAccessDeniedHandler();
}
}

关于java - 处理 Spring Boot 资源服务器中的安全异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41140669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com