如果您想处理身份验证过程,您可以设置自己的自定义身份验证管理器
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password authentication-manager-ref="customAuthenticationManager" />
</oauth:authorization-server>
<authentication-manager id="customAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
<bean id="customAuthenticationProvider"
class="com.any.CustomAuthenticationProvider">
</bean>
创建实现的自定义身份验证提供程序AuthenticationProvider
public class UserAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String username = auth.getName();
String password = token.getCredentials().toString();
User user = userService.loadByUsername(username);
if(user.isLocked){
throw new UserLockedException("User is locked");
}
if(another.something.bad.happened){
throw new AnotherSomethingBadHappenedException("Error");
}
// setup authorities
//...
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
}
现在您有了自己的异常,通过使用 ExceptionMapper,您可以将身份验证过程中引发的异常转换为自定义响应消息。
您可以创建的另一个自定义是在授权过程中,通过创建扩展的自定义类ApprovalStoreUserApprovalHandler
public class CustomUserApprovalHandler extends ApprovalStoreUserApprovalHandler {
// stripped
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
Authentication userAuthentication) {
ClientDetails client = clientDetailsService
.loadClientByClientId(authorizationRequest.getClientId());
// here, you have the client and the user
// you can do any checking here and throw any exception
authorizationRequest.setApproved(approved);
return authorizationRequest;
}
}
为该类创建 bean 定义
<bean id="userApprovalHandler"
class="com.any.CustomUserApprovalHandler">
<property name="approvalStore" ref="approvalStore" />
<property name="requestFactory" ref="oAuth2RequestFactory" />
<property name="clientDetailsService" ref="clientDetails" />
<property name="useApprovalStore" value="true" />
</bean>