在Spring Security中注册自定义身份验证的惯用方法
我的用例是使用SpringSecurity5.2的Oauth2登录,但希望我的数据库用户类与身份验证中的Oauth2AuthenticationToken一起可用。这是为了让SecurityContextHolder缓存我的数据库用户类 在伪代码中:在Spring Security中注册自定义身份验证的惯用方法,spring,spring-security,spring-security-oauth2,Spring,Spring Security,Spring Security Oauth2,我的用例是使用SpringSecurity5.2的Oauth2登录,但希望我的数据库用户类与身份验证中的Oauth2AuthenticationToken一起可用。这是为了让SecurityContextHolder缓存我的数据库用户类 在伪代码中: 用户使用Google或Github Oauth2登录 我的应用程序使用返回的信息查找(或创建)数据库用户 我的应用程序向SecurityContextHolder保存一个自定义身份验证包装器,该包装器包装Oauth2AuthenticationTo
class MyAuthenticationWrapper implements Authentication {
public MyAuthenticationWrapper(User user, Authentication underlyingAuth1) {
this.user = user;
this.underlyingAuth = underlyingAuth1;
}
private final User user;
private final Authentication underlyingAuth;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return underlyingAuth.getAuthorities();
}
@Override
public void setAuthenticated(boolean isAuthenticated) {
underlyingAuth.setAuthenticated(isAuthenticated);
}
@Override
public String getName() {
return underlyingAuth.getName();
}
@Override
public Object getCredentials() {
return underlyingAuth.getCredentials();
}
@Override
public Object getPrincipal() {
return underlyingAuth.getPrincipal();
}
@Override
public boolean isAuthenticated() {
return underlyingAuth.isAuthenticated();
}
@Override
public Object getDetails() {
return underlyingAuth.getDetails();
}
public User getUser() {
return user;
}
}
类MyAuthenticationWrapper实现身份验证{
公共MyAuthenticationWrapper(用户,身份验证基础Auth1){
this.user=用户;
this.underyingauth=underyingauth1;
}
私有最终用户;
基于身份验证的私有最终身份验证;
@凌驾
public Collection也许查看一下
OAuth2UserService
会有所帮助。它在成功获取OAuth令牌后被调用。它的工作原理如下:
OAuth2UserService
作为一个bean(它将自动获取),负责处理数据库:
@Component
public class CustomService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest)
throws OAuth2AuthenticationException {
// ... DB logic goes here
}
}
有关您正在处理的核心类的更多信息,以下内容可能会有所帮助:
OAuth2UserService
的开箱即用实现,请查看:
OAuth2UserService
会有所帮助。它在成功获取OAuth令牌后被调用。这就是它的工作方式:
OAuth2UserService
作为一个bean(它将自动获取),负责处理数据库:
@Component
public class CustomService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest)
throws OAuth2AuthenticationException {
// ... DB logic goes here
}
}
有关您正在处理的核心类的更多信息,以下内容可能会有所帮助:
OAuth2UserService
的开箱即用实现,请查看:
OAuth2LoginAuthenticationToken auth = //...
OAuth2User user = auth.getPrincipal();