实现 Spring OAuth2,从不同设备获取相同的访问令牌

Cor*_*ral 4 spring spring-security spring-security-oauth2

实现了 Spring OAuth2 安全性,并在使用同一用户但从不同设备登录时获得相同的访问令牌。当我从这些设备中的任何一个注销(撤销令牌)时,其他设备也被注销。这是预期的行为还是我遗漏了什么?希望共享大量代码不会有太大帮助,因此请保持问题简短。

Man*_*kus 5

DefaultTokenServices 的默认行为是重用现有令牌(基于现有 TokenStore 实现的行为)

http://forum.spring.io/forum/spring-projects/security/oauth/121797-multiple-valid-oauth-access-tokens-for-same-client

如果您希望每个设备都不同,access_token则创建您自己AuthenticationKeyGenerator的设备,例如在授权过程中发送您的设备 ID,并让您AuthenticationKeyGenerator处理该设备 ID 以创建access_token特定于该设备的设备 ID 。


小智 5

(请阅读org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator代码以将以下解决方案放入上下文中)

DefaultAuthenticationKeyGenerator春天有售。我刚刚创建了一个带有一个扩展的相同代码的自定义版本,即device_id从客户端发送的作为请求参数的检索OAuth2Authentication如下;

String deviceId = authentication.getOAuth2Request().getRequestParameters().get("device_id")

然后放入valuesmap中(用于最终生成token)。因此,它device_id成为token每个设备产生唯一令牌的一部分。

以下是完整的解决方案,主要是DefaultAuthenticationKeyGenerator除了上面解释的位之外。

public class CustomAuthenticationKeyGenerator implements AuthenticationKeyGenerator
{
    private static final String CLIENT_ID = "client_id";

    private static final String SCOPE = "scope";

    private static final String USERNAME = "username";

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(authorizationRequest.getScope()));
        }

        String deviceId = authorizationRequest.getRequestParameters().get(CustomHeader.device_id.name());
        if(deviceId != null && !deviceId.isEmpty()) {
            values.put("device_id", deviceId);
        }

        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
        }

        try {
            byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
            return String.format("%032x", new BigInteger(1, bytes));
        }
        catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)