【问题标题】:Decrypt and revalidate JWT Token in Java在 Java 中解密和重新验证 JWT 令牌
【发布时间】:2021-03-07 02:55:00
【问题描述】:

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

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

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

提前谢谢你。

【问题讨论】:

标签: java azure jwt token


【解决方案1】:

如果要验证 Azure AD 令牌,如果要验证 Azure AD 访问令牌,我们可以尝试使用 sdk java-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("<>");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 2016-01-30
    • 2019-09-08
    • 2013-09-11
    • 2019-06-23
    • 1970-01-01
    • 2019-06-02
    • 2016-08-16
    相关资源
    最近更新 更多