我正在使用Spring Authorization Server并在用户登录时实现自定义AuthenticationProvider
,如下所示:
@Component
public class AuthenticationCallout implements AuthenticationProvider {
private static final Logger LOG = LoggerFactory.getLogger(AuthenticationCallout.class);
@Autowired
private JpaOAuth2AuthorizationService jpaOAuth2AuthorizationService;
private WebClient.Builder webClientBuilder;
public AuthenticationCallout(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
LOG.info("authenticate with username and password");
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
LOG.info("authorities: {}, details: {}, credentials: {}", authentication.getAuthorities(),
authentication.getDetails(), authentication.getCredentials());
if (name.equals("admin") && password.equals("system")) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
LOG.info("returning using custom authenticator");
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;
} else {
return null;
}
}
我还想获取此用户登录时使用的clientId。获取clientId的最佳方法是什么?在这个自定义身份验证中,我将对另一个服务进行webclient调用,该服务将用户密码与系统的clientId存储在一起。
1条答案
按热度按时间kq0g1dla1#
有很多方法可以解决这个问题。例如,将您自己的
Filter
添加到Spring Security过滤器链中,您可以直接访问HttpServletRequest
和HttpServletResponse
。但是,您也可以通过Spring的RequestContextHolder
在非过滤器组件中访问它。最简单的开始方式是实现
UserDetailsService
,并通过RequestCache
访问用于启动流的SavedRequest
,如下所示:UserDetailsService
可以从外部服务查找用户。这需要哈希密码作为微服务响应的一部分,因此DaoAuthenticationProvider
可以在本地验证密码。