解密并重新验证java中的jwt令牌

ao218c7q  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(351)

我是azure、jwt、microsoft identity platform的新手。
我需要解密一个jwt令牌,并验证该令牌是从azure生成的,而不是在我的普通旧java代码中手动创建的。
我浏览了微软的文档,但没有一个涉及到技术实现。我真的非常需要帮助。
先谢谢你。

fruv7luv

fruv7luv1#

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

相关问题