实施Spring OAuth2安全性并在使用相同用户但从不同设备进行日志记录时获取相同的访问令牌。当我从这些设备中的任何一个注销(撤销令牌)时,其他设备也会被注销。这是预期的行为还是我错过了什么?希望共享大量代码不会有太多帮助,因此保持简短的问题。
DefaultTokenServices的默认行为是重用现有令牌(基于现有TokenStore实现的行为)
如果你想给每个设备不同的access_token
然后创建自己的AuthenticationKeyGenerator
,例如在授权过程中发送您的设备ID,并让您的AuthenticationKeyGenerator
处理该设备ID以创建特定于该设备的access_token
。
(请阅读org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator
代码以将以下解决方案置于上下文中)
DefaultAuthenticationKeyGenerator
是春季推出的。我刚刚使用相同的代码创建了一个带有一个扩展名的自定义版本,即从客户端发送的device_id
作为请求参数从OAuth2Authentication
检索如下;
String deviceId = authentication.getOAuth2Request().getRequestParameters().get("device_id")
然后被放入values
地图(最终用于生成令牌)。因此,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).");
}
}
}
对于那些面临同样问题的人可以使用MangEngkus的回复解决方案,为了获得精确的解决方案,您也可以参考此链接Spring OAuth2 Generate Access Token per request to the Token Endpoint