简体   繁体   English

验证 Azure AD JWT 访问令牌时出错

[英]Error validating Azure AD JWT access token

I have an Azure AD JWT token that is obtained using Msal library but when I try to validate this token something is wrong:我有一个使用 Msal 库获取的 Azure AD JWT 令牌,但是当我尝试验证此令牌时出现问题:

Client: A Sharepoint Web Part客户端: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;

On the other hand I have a server app (Java) where the access token is validated另一方面,我有一个服务器应用程序(Java),其中验证了访问令牌

Validator:验证器:

<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>

Code代码

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

My problem is that when I try to validate this token I obtained this error: The Token's Signature resulted invalid when verified using the Algorithm: SHA256withRSA我的问题是,当我尝试验证此令牌时,我收到此错误:使用算法验证时令牌的签名无效:SHA256withRSA

I'm stuck with this, If the token is right, Why I have this error?我坚持这个,如果令牌是正确的,为什么我有这个错误?

Regards问候

Finally, It works with something like this.最后,它适用于这样的事情。

  1. To obtain the token (using adal in the Web Part):要获取令牌(在 Web 部件中使用 adal):

     // Obtaining token provider let tp = await this.context.aadTokenProviderFactory.getTokenProvider(); let config = tp["_defaultConfiguration"]; let aadInstanceUrl = config.aadInstanceUrl[length - 1] === "/" ? config.aadInstanceUrl : config.aadInstanceUrl + "/"; // Config context let ctx = new AuthenticationContext({ tenant: tenantId, clientId: clientId, instance: aadInstanceUrl, redirectUri: config.redirectUri, extraQueryParameter: "login_hint=" + encodeURIComponent(loginName), loadFrameTimeout: 60000 }); // Check user let cu = ctx.getCachedUser(); console.log("USER", cu, loginName, ctx); if (cu && cu.userName.toLowerCase() !== loginName.toLowerCase()) { console.log("Clean user cache"); ctx.clearCache(); } // Login process console.log("Login process"); // Obtaining Azure AD Token let azureADToken = this.acquireToken(ctx, clientId);
  2. To validate the token:要验证令牌:

     String token = "XXXXXX"; 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()); } System.out.println("works!");

With this dependencies:有了这个依赖:

  <dependencies>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
            <version>0.11.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.10</version>
            <type>bundle</type>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
            <type>bundle</type>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.10</version>
            <type>bundle</type>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
        </dependency>
        <!-- JUNIT -->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <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>

        <!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.2</version>
        </dependency>

    </dependencies>

I noticed that the scope is user.read which means the token is for Microsoft Graph API.我注意到范围是user.read ,这意味着令牌用于 Microsoft Graph API。

Please note:请注意:

If you're a client getting a token for Graph, assume that it's an encrypted string that you should never look at - sometimes it will be.如果您是为 Graph 获取令牌的客户,请假设它是一个您永远不应该查看的加密字符串 - 有时它会。 We use a special token format for Graph that they know how to validate - you shouldn't be looking at access tokens if they're not for you.我们为 Graph 使用一种特殊的令牌格式,他们知道如何验证 - 如果它们不适合您,您不应该查看访问令牌。

You can use this access token to call Microsoft Graph API directly, if the token is wrong, you will get the response from Microsoft API server.您可以使用此访问令牌直接调用 Microsoft Graph API,如果令牌错误,您将收到来自 Microsoft API 服务器的响应。

Reference:参考:

https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609#issuecomment-529537264 https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609#issuecomment-529537264

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM