gpt4 book ai didi

azure - 如何使用 Java 验证 Azure AD JWT token ?

转载 作者:行者123 更新时间:2023-12-02 05:52:45 25 4
gpt4 key购买 nike

我有一个使用 Msal 库获取的 Azure AD JWT token ,但当我尝试验证此 token 时出现错误:

客户端:Sharepoint Web 部件

 const config = {
auth: {
clientId: "xxxxx",
authority: "https://login.microsoftonline.com/yyyyyy"
}
};

const myMSALObj = new UserAgentApplication(config);

let accessTokenRequest = {
scopes: ["user.read"],
loginHint: this.context.pageContext.user.loginName,
extraQueryParameters: {domain_hint: 'organizations'}
}

myMSALObj.acquireTokenSilent(accessTokenRequest).then(
function(accessTokenResponse) {
// Acquire token silent success
let accessToken = accessTokenResponse.accessToken;

我正在尝试从以下位置检索公钥: https://login.microsoftonline.com/tenant-id/.well-known/openid-configuration但使用这个公钥我永远无法重定向到:https://login.microsoftonline.com/common/discovery/keys

这种情况下还有其他方法获取公钥吗?

服务器:验证

public PublicKey getPublicKeyFromParams(String e, String n){

byte[] modulusBytes = Base64.getUrlDecoder().decode(n);

BigInteger modulusInt = new BigInteger(1, modulusBytes);

byte[] exponentBytes = Base64.getUrlDecoder().decode(e);

BigInteger exponentInt = new BigInteger(1, exponentBytes);

KeyFactory keyFactory;

RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(modulusInt, exponentInt);

try {

keyFactory = KeyFactory.getInstance("RSA");

return keyFactory.generatePublic(publicSpec);

} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {

ex.printStackTrace();

}

return null;

}

@Test

public void name() throws Exception {

String jwt = "xxxxxxx";

KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);

String e = Base64.getUrlEncoder().encodeToString((((RSAPublicKeyImpl) keyPair.getPublic()).getPublicExponent()).toByteArray());

String n = Base64.getUrlEncoder().encodeToString((((RSAPublicKeyImpl) keyPair.getPublic()).getModulus()).toByteArray());

System.out.println("Public Key: " + Base64.getUrlEncoder().encodeToString(keyPair.getPublic().getEncoded()));

System.out.println("Public Key Exponent: " + e);

System.out.println("Public Key Modulus: " + n);

String jws = Jwts.builder().setSubject("pepe").signWith(keyPair.getPrivate()).compact();

System.out.println("Generated JWS:" + jws);

PublicKey publicKey = getPublicKeyFromParams(e, n);

Jwt parsedJWs = Jwts.parserBuilder().setSigningKey(publicKey).build().parse(jws);

System.out.println("Parsed JWS: " + parsedJWs);

publicKey = getPublicKeyFromParams(eValue, nValue);

System.out.println("Azure PublicKey fron n-e: " + publicKey);

CertificateFactory factory = CertificateFactory.getInstance("X.509");

Certificate cert = factory.generateCertificate(new ByteArrayInputStream(

DatatypeConverter.parseBase64Binary("cccccccccccccccccc")));

publicKey = cert.getPublicKey();

System.out.println("Azure PublicKey from x5c: " + publicKey);

Jwt jwtParsed = Jwts.parserBuilder().setSigningKey(publicKey).build().parse(jwt);

System.out.println(jwtParsed);

}

public static PublicKey getPublicKey(String key){

try{

byte[] byteKey = Base64.getDecoder().decode(key);

X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);

KeyFactory kf = KeyFactory.getInstance("RSA");

return kf.generatePublic(X509publicKey);

}

catch(Exception e){

e.printStackTrace();

}

return null;

}

最佳答案

如果您想验证Azure AD访问 token ,我们可以尝试使用sdk java-jwtjwks-rsa来实现。

例如

  1. 通过maven安装SDK
 <dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>8.6.2</version>
</dependency>

<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.11.0</version>
</dependency>
  • 代码

    a.验证签名

     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/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());

    }
  • 关于azure - 如何使用 Java 验证 Azure AD JWT token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60884823/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com