我有具有OAuth2.0授权的Spring Boot应用程序(2.0.2.RELEASE)。
我需要处理如下异常
{
“错误”:“ invalid_token”,
“ error_description”:“访问令牌已过期:eyJhbGc ...”}
{
“错误”:“未经授权”,
“ error_description”:“访问此资源需要完全认证”}
我正在尝试做的是:
@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.");
}
}