java - 处理ResourceServer中的spring security认证异常

标签 java spring security exception

我有具有 OAuth2.0 授权的 Spring Boot 应用程序 (2.0.2.RELEASE)。 我需要像下面这样处理异常

{ "error": "invalid_token", "error_description": "Access token expired: eyJhbGc..." }

{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }

我正在尝试做什么:

@SpringBootApplication
@EnableEurekaClient
@EnableResourceServer
public class CatalogServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(CatalogServiceApplication.class, args);
    }
}

配置:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint());
    }

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
            System.out.println("!!!!!!!!!!!IT WORKS!!!!!!!!!!!!");
           response.sendError(response.SC_UNAUTHORIZED,
                "Sorry, You're not authorized to access this resource.");
        }
    }

但是它不起作用。 “开始”方法不是调用。

最佳答案

每个请求都使用 HTTP 基本身份验证进行身份验证。如果身份验证失败,将使用配置的 AuthenticationEntryPoint 重试身份验证过程。

此问题未在 securityConfig 中共享AuthenticationEntryPoint。可以使用 @Component 来解决 @Autowired

配置:

SpringSecurityConfig

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint authEntryPoint;        

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(authEntryPoint);
    }

AuthenticationEntryPoint

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
           System.out.println("!!!!!!!!!!!IT WORKS!!!!!!!!!!!!");
           response.sendError(response.SC_UNAUTHORIZED,
                "Sorry, You're not authorized to access this resource.");
        }
    }

关于java - 处理ResourceServer中的spring security认证异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50941942/

相关文章:

java - 对 java if else 性能感到困惑

java - 将单独的组件锚定在 JFrame 中

java - Flowable服务任务中的spring bean注入(inject)问题

java - 为什么我的 Spring Batch 应用程序无法处理?

java - 转换时间字段 H :M into integer field (minutes) in JAVA

java - 复制 View 以创建 View 的精确副本。相对于屏幕移动 View

java - Spring 3.1没有xml,只是配置不起作用

security - 使用单独的寄存器来存储返回地址?

security - symfony 安全性限制对指定 ip 集的路由列表的访问

security - 使用另一台服务器存储文件: Good or bad idea?