gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:06:10 26 4
gpt4 key购买 nike

我有具有 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/

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