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;
}
}
RUPAuthenticator
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);
}
これがあなたが探していたものであることを願っています。