首页 > 解决方案 > 在 Java 中解密和重新验证 JWT 令牌

问题描述

我是 Azure、JWT、Microsoft 身份平台的新手。

我需要解密 JWT 令牌并验证该令牌是从 Azure 生成的,而不是在我的普通旧 Java 代码中手动创建的。

我浏览了 Microsoft 文档,但没有人谈论技术实现。我非常非常需要帮助。

先感谢您。

标签: javaazurejwttoken

解决方案


如果要验证 Azure AD 令牌,如果要验证 Azure AD 访问令牌,我们可以尝试使用 sdkjava-jwtjwks-rsa实现它。

例如

  1. 安装 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>
  1. 代码
// 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("<>");

推荐阅读