【发布时间】:2019-08-05 19:03:10
【问题描述】:
在我的 Spring Boot Web 应用程序中,我点击了第三方服务进行授权,而我的应用程序只是一个内容提供者。父应用程序使用站点管理员进行身份验证。我的应用程序在标头中获取用户 ID,并调用第三方 api 以设置 UserDetails 与权限。
我的要求是在第三方授权服务关闭时处理场景。目前在这种情况下,我将 UserDetails 设置为没有角色,并且由于每个端点都受授权绑定,因此如果用于授权的第三方服务关闭,我会得到 403。
但如果用户缺乏授权并且授权服务已关闭,我想显示不同的消息。
如果我通过从 UserDetailsServiceImpl -> loadUserByUserName() 抛出自定义异常来处理授权服务,则 RequestHeaderAuthenticationFilter 遇到此异常并且请求被过滤掉。知道如何完成这项工作吗?
安全配置
public class WebSecurityCustomConfig extends WebSecurityConfigAdapter {
private UserDetailsService userDetails;
protected void configure(HttpSecurity http) {
http.csrf().disable().authorizeRequests().antMatchers("/*).permitAll()
.anyRequests()
.hasAnyAuthority("MODULEX","MODULEY");
http.addFilterBefore(requestHeaderAuthFilter(),
BasicAuthenticationFilter.class);
http.exceptionHandling().authenticationEntryPoint(customEntryPoint());
}
protect void configure(AuthenticationManagerBuilder builder) {
PreAuthenticaticatedAuthenticationProvider auth = new
PreAuthenticaticatedAuthenticationProvider ();
auth.setPreAuthenticatedUserDetailsService(new
UserDetailsByNameServiceWrapper<>(userDetails));
}
}
自定义 UserDetailsService
public class CustomUserDetailsService implements UserDetailsService {
private final AuthorizationService authService;
@Inject
public CustoUserDetailsService(AuthorizationService authService) {
this.authService = authService;
}
public UserDetails loadUserByUsername(String username) {
return new User(username, "",
authService.getAuthorities(username));
// authService is a third party jar and if their upstream service
//is down , it throws a runtime exception
}
}
如果我按以下方式处理他们的错误,那么我最终会得到 403,但如果服务关闭,我想要 503,如果用户没有正确权限访问他正在访问的端点,我想要 403。
当前处理身份验证服务异常
public UserDetails loadUserByUsername(String username) {
try{
return new User(username, "",
authService.getAuthorities(username));
}
catch(AuthServiceException e) {
return new User(username, "",
Collections.emptyList());
}
}
【问题讨论】:
-
如果我从 userdetailsservice 抛出异常而不是处理,那么它不会命中 CustomauthenticationEntryPoint 可用于在服务关闭时做出适当的响应
-
上述实现用户没有权限,如果授权看到同样的错误是错误的
标签: spring spring-boot spring-security