java - 在 Java 中解密和重新验证 JWT 令牌
问题描述
我是 Azure、JWT、Microsoft 身份平台的新手。
我需要解密 JWT 令牌并验证该令牌是从 Azure 生成的,而不是在我的普通旧 Java 代码中手动创建的。
我浏览了 Microsoft 文档,但没有人谈论技术实现。我非常非常需要帮助。
先感谢您。
解决方案
如果要验证 Azure AD 令牌,如果要验证 Azure AD 访问令牌,我们可以尝试使用 sdkjava-jwt
并jwks-rsa
实现它。
例如
- 安装 SDK
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.11.0</version>
</dependency>
- 代码
// validate signature
String token="<your AD token>";
DecodedJWT jwt = JWT.decode(token);
System.out.println(jwt.getKeyId());
JwkProvider provider = null;
Jwk jwk =null;
Algorithm algorithm=null;
try {
provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/v2.0/keys"));
jwk = provider.get(jwt.getKeyId());
algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
algorithm.verify(jwt);// if the token signature is invalid, the method will throw SignatureVerificationException
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JwkException e) {
e.printStackTrace();
}catch(SignatureVerificationException e){
System.out.println(e.getMessage());
}
// get claims
String token="<your AD token>";
DecodedJWT jwt = JWT.decode(token);
Map<String, Claim> claims = jwt.getClaims(); //Key is the Claim name
Claim claim = claims.get("<>");
推荐阅读
- sql - 我收到“未为参数 1 指定值”和 2 错误,您能告诉我这里哪里出错了吗?
- python - 如果我输入错误的凭据一次,它不会再次验证凭据,我认为是因为它不再检查 acc_number 和 acc_pass 之后,
- ios - 如何使用 watchos6 实时读取/写入氧饱和度
- powershell - 在 Powershell 中,获取连接路径以使用 $null 和空字符串
- sql - 是否存在可用作自定义自动收报机的应用程序/Windows 小部件?
- c++ - Cout 不生成任何东西(多项式插值)
- spring-boot - JBoss 忽略在 MANIFEST.MF of war 应用程序中声明的 Main-Class 和 Start-Class 属性
- html - 想要将照片中的文字更多地移动到中心
- r - 在条形图的 X 轴中添加低于月份的年份
- java - 声音一遍又一遍地开始