我正在使用 Spring Security OAuth2。客户端应用程序(我们拥有的)发出一个“密码”授权请求,该请求传递用户的用户名和密码。就像草案规定的那样。
我需要这种机制来支持其他类型的凭据,例如卡号、PIN,甚至是预认证的、不需要密码的授权。
请记住,这些请求仅由特权 client_id 允许,该特权仅在我们拥有的应用程序中使用。
我正在使用 Spring Security OAuth2。客户端应用程序(我们拥有的)发出一个“密码”授权请求,该请求传递用户的用户名和密码。就像草案规定的那样。
我需要这种机制来支持其他类型的凭据,例如卡号、PIN,甚至是预认证的、不需要密码的授权。
请记住,这些请求仅由特权 client_id 允许,该特权仅在我们拥有的应用程序中使用。
戴夫,感谢您的快速回复。我实际上找到了完美的解决方案,您参与了。它与“自定义授予”令牌授予者有关...... https://jira.spring.io/browse/SECOAUTH-347
如果我更新了我相当旧的 1.0.0.M5 版本,我可能已经知道这些了。
我的方法是扩展AbstractTokenGranter
一个支持自定义授权类型的类(我称之为“studentCard”)。一旦身份验证请求出现在此处,我将像 一样检查参数列表ResourceOwnerPasswordTokenGranter
,而是查找我的自定义“cardNumber”参数。然后我将我自己的基于 id 的版本传递UsernamePasswordAuthenticationToken
给我的 AuthenticationProvider,它知道如何根据 id 卡对用户进行身份验证。
这是我想出的自定义令牌授予者类:
public class StudentCardTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "studentCard";
private final AuthenticationManager authenticationManager;
public StudentCardTokenGranter(AuthenticationManager authenticationManager,
AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService) {
super(tokenServices, clientDetailsService, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) {
Map<String, String> parameters = clientToken.getAuthorizationParameters();
String cardNumber = parameters.get("cardNumber");
Authentication userAuth = new StudentCardAuthenticationToken(cardNumber);
try {
userAuth = authenticationManager.authenticate(userAuth);
} 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 student: " + cardNumber);
}
return new OAuth2Authentication(clientToken, userAuth);
}
}
我的授权服务器配置:
<!-- Issues tokens for both client and client/user authorization requests -->
<oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password authentication-manager-ref="myUserManager" />
<oauth:custom-grant token-granter-ref="studentCardGranter" />
</oauth:authorization-server>
<bean id="studentCardGranter" class="com.api.security.StudentCardTokenGranter">
<constructor-arg name="authenticationManager" ref="myUserManager" />
<constructor-arg name="tokenServices" ref="tokenServices" />
<constructor-arg name="clientDetailsService" ref="clientDetails" />
</bean>
该规范没有明确允许在客户端和身份验证服务器之间直接、非基于密码的用户令牌直接交换。我认为将密码授予扩展到其他形式的身份验证是很自然的。这是规范的精神,如果不是按字面意思的话,所以如果你拥有关系的双方,那就没有太大的问题了。Spring OAuth 不明确支持以这种方式扩展密码授予的任何东西,但它并不难做到(它实际上只是关于 /token 端点的安全性)。我见过的另一种方法是坚持密码授予协议,但使“密码”成为客户端只能通过知道用户已通过其中一种替代方式进行身份验证才能获得的一次性令牌。