我只是为此而挣扎,并认为我分享了它。
如果你使用maven,请将其添加到您的pom中.xml
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.4.0</version>
</dependency>
如果您使用渐变添加
compile 'com.auth0:jwks-rsa:0.4.0'
compile 'com.auth0:java-jwt:3.3.0'
创建实现 RSAKeyProvider 的类
import com.auth0.jwk.JwkException;
import com.auth0.jwk.JwkProvider;
import com.auth0.jwk.JwkProviderBuilder;
import com.auth0.jwt.interfaces.RSAKeyProvider;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class AwsCognitoRSAKeyProvider implements RSAKeyProvider {
private final URL aws_kid_store_url;
private final JwkProvider provider;
public AwsCognitoRSAKeyProvider(String aws_cognito_region, String aws_user_pools_id) {
String url = String.format("https://cognito-idp.%s.amazonaws.com/%s/.well-known/jwks.json", aws_cognito_region, aws_user_pools_id);
try {
aws_kid_store_url = new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException(String.format("Invalid URL provided, URL=%s", url));
}
provider = new JwkProviderBuilder(aws_kid_store_url).build();
}
@Override
public RSAPublicKey getPublicKeyById(String kid) {
try {
return (RSAPublicKey) provider.get(kid).getPublicKey();
} catch (JwkException e) {
throw new RuntimeException(String.format("Failed to get JWT kid=%s from aws_kid_store_url=%s", kid, aws_kid_store_url));
}
}
@Override
public RSAPrivateKey getPrivateKey() {
return null;
}
@Override
public String getPrivateKeyId() {
return null;
}
}
现在,您可以通过以下方式验证令牌
String aws_cognito_region = "us-east-1"; // Replace this with your aws cognito region
String aws_user_pools_id = "us-east-1_7DEw1nt5r"; // Replace this with your aws user pools id
RSAKeyProvider keyProvider = new AwsCognitoRSAKeyProvider(aws_cognito_region, aws_user_pools_id);
Algorithm algorithm = Algorithm.RSA256(keyProvider);
JWTVerifier jwtVerifier = JWT.require(algorithm)
//.withAudience("2qm9sgg2kh21masuas88vjc9se") // Validate your apps audience if needed
.build();
String token = "eyJraWQiOiJjdE.eyJzdWIiOiI5NTMxN2E.VX819z1A1rJij2"; // Replace this with your JWT token
jwtVerifier.verify(token);
请注意,JwkProviderBuilder将使用LRU缓存构建一个JwkProvider,该缓存缓存从aws密钥存储中检索到的密钥,这非常整洁!缓存规则可以使用构建器进行更改。
[更新]将创建JwkProvider移动到构造函数,以便将缓存视为@danieln注释