我如何必须实现/扩展 AuthenticationProvider 才能从 Authentication 对象中读取自定义数据?
RealmAuthenticationProvider
public class RealmAuthenticationProvider implements AuthenticationProvider {
private RUPAuthenticator rupAuthenticator;
public RealmAuthenticationProvider(RUPAuthenticator rupAuthenticator) {
this.rupAuthenticator = rupAuthenticator;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Object principal = authentication.getPrincipal();
Object credentials = authentication.getCredentials();
Object realm = authentication.getDetails();
if (rupAuthenticator.authenticate(principal, credentials, realm)) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); //use any GrantedAuthorities you need
return new RealmAuthenticationToken(principal, credentials, realm, grantedAuths);
};
return null;
}
@Override
public boolean supports(Class<?> authentication) {
return RealmAuthenticationToken.class.isAssignableFrom(authentication);
}
}
RealmAuthenticationToken
public class RealmAuthenticationToken extends UsernamePasswordAuthenticationToken {
private Object realm;
public RealmAuthenticationToken(Object principal, Object credentials, Object realm, Collection<? extends GrantedAuthority> authorities) {
super(principal,credentials, authorities);
this.realm = realm;
}
}
RUP身份验证器
public interface RUPAuthenticator {
boolean authenticate(Object username, Object password, Object realm);
}
您只需为 RUPAuthenticator 提供一个实现,该实现说明用户名、密码、领域组合是否正确。
然后将自定义的AuthenticationProvider(RealmAuthenticationProvider)注册为一个bean。以下是接受来自特定用户的请求的身份验证提供程序的示例:
@Bean
public AuthenticationManager authenticationManager() {
List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>();
providers.add(new RealmAuthenticationProvider(new RUPAuthenticator() {
@Override
public boolean authenticate(Object username, Object password, Object realm) {
return (username.equals("sa") && password.equals("sa") && realm.equals("realm2"));
}
}));
return new ProviderManager(providers);
}
我希望这就是你要找的。