你需要创建一个UsernamePasswordCountryAuthenticationToken
。
public class UsernamePasswordCountryAuthenticationToken extends UsernamePasswordAuthenticationToken {
private String country;
public UsernamePasswordCountryAuthenticationToken(Object principal, Object credentials, String country, Collection<? extends GrantedAuthority> authorities) {
super(principal, credentials, country, authorities);
}
public UsernamePasswordCountryAuthenticationToken(Object principal, Object credentials, String country) {
super(principal, credentials, country);
}
public String getCountry() {
return country;
}
}
,并覆盖ResourceOwnerPasswordTokenGranter
public class CustomResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "password";
private final AuthenticationManager authenticationManager;
public CustomResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager,
AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService) {
super(tokenServices, clientDetailsService, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) {
Map<String, String> parameters = clientToken.getAuthorizationParameters();
String username = parameters.get("username");
String password = parameters.get("password");
String country = parameters.get("country");
Authentication userAuth = new UsernamePasswordCountryAuthenticationToken(username, password, country);
try {
userAuth = authenticationManager.authenticate(userAuth);
} catch (AccountStatusException ase) {
//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
throw new InvalidGrantException(ase.getMessage());
} catch (BadCredentialsException e) {
// If the username/password are wrong the spec says we should send 400/bad grant
throw new InvalidGrantException(e.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + username);
}
return new OAuth2Authentication(clientToken, userAuth);
}
}
在你的春季安全的OAuth配置文件
<bean id="customResourceOwnerPasswordTokenGranter" class="CustomResourceOwnerPasswordTokenGranter">
<constructor-arg index="0" ref="authenticationManager"/>
<constructor-arg index="1" ref="tokenServices"/>
<constructor-arg index="2" ref="clientDetailsService"/>
</bean>
<oauth:authorization-server ...>
<oauth:custom-grant token-granter-ref="customResourceOwnerPasswordTokenGranter" />
</oauth:authorization-server>
现在
最后,如果你已经正确配置AuthenticationManager
有您的自定义AuthenticationProvider
,你会接收UsernamePasswordCountryAuthenticationToken
至AuthenticationProvider.authenticate method(Authentication auth)
的实例,您可以在其中投射auth
到UsernamePasswordCountryAuthenticationToken
并且使用。