OAuth2 是否允许使用非密码或自定义凭据进行授权?

2024-04-06

我正在使用 Spring Security OAuth2。客户端应用程序(我们拥有的)发出“密码”授予请求,传递用户的用户名和密码。正如草案所规定的那样。

我需要此机制还支持其他类型的凭据,例如卡号、PIN 码,甚至是预先验证的、无需密码的授权。

请记住,这些请求只能由特权 client_id 允许,该 client_id 只能在我们拥有的应用程序中使用。


戴夫,感谢您的快速回复。我实际上找到了完美的解决方案,您也参与了其中。它与“自定义授予”令牌授予者有关......https://jira.spring.io/browse/SECOAUTH-347 https://jira.spring.io/browse/SECOAUTH-347

如果我更新了相当旧的 1.0.0.M5 版本,我可能会知道这些。

我的方法是延长AbstractTokenGranter具有支持自定义授予类型的类(我称之为“studentCard”)。一旦身份验证请求到达这里,我就会检查参数列表,就像ResourceOwnerPasswordTokenGranter,而是查找我的自定义“cardNumber”参数。然后我传递我自己的基于 id 的版本UsernamePasswordAuthenticationToken到我的 AuthenticationProvider,它知道如何根据身份证对用户进行身份验证。

这是我想出的自定义令牌授予者类:

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OAuth2 是否允许使用非密码或自定义凭据进行授权? 的相关文章

随机推荐