【发布时间】:2017-11-15 00:21:05
【问题描述】:
我正在运行一个使用 OAuth2 保护的 Spring Boot REST API。
这是我对访问令牌和刷新令牌的要求的实际工作 100% 配置:
@Configuration
public class ServerSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
@Autowired
CustomPasswordEncoder passwordEncoder;
@Autowired
CustomUserDetailsService userDetailsService;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
}
我现在需要添加一个预认证配置,所以登录它只有在某些配置可用时才可用。
我很困惑是否需要覆盖 AuthenticationManager 或 AuthenticationProvider
我尝试在上面的同一个类中添加这样的 CustomAuthenticationProvider:
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.authenticationProvider(authProvider)
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
// @formatter:on
}
然后:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (allowLogin()) {
// Should call the UserDetailService as normally workflow.
return null;
}
throw new AuthenticationServiceException("Out of service");
}
private boolean allowLogin() {
//Custom logic
return false;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
但是当我抛出异常时,无论如何都会触发我的 UserDetailService。所以这不是一个选项,或者我可能以错误的方式实施。
实现 CustomAuthenticationManager 怎么样?我不知道在哪里调用它。
我试图避免在 UserDetailService 的 loadByUsername 方法中引发异常,因为如果有人已经获得令牌,那么他仍然可以使用我的 API。也许我必须在两个进程中创建逻辑?
更新
我认为我需要做的是添加一个CustomAccessDecisionVoter,但不知道在哪里为资源服务器配置。
【问题讨论】:
标签: spring authentication spring-boot spring-security