Verify a JWT token

Updated at:

Prerequisites

  1. Create an Alibaba Cloud account, complete real-name verification, create a Secure Authentication instance, and then create an application for the instance.

  2. Obtain an AccessKey pair of the Alibaba Cloud account.

Validating a JWT

Verifies a JSON Web Token (JWT) token. The token is returned after identity authentication is passed using a mobile client SDK.

Request parameters

Name

Type

Required

Example value

Description

ApplicationExternalId

String

Yes

A0000001

The application ID. The ID is specified when you create the application. You can view the ID in the details panel of the application.

JwtIdToken

String

Yes

This is returned after a successful authentication call to the mobile SDK. Currently, it is available only for IFAA and phone number authentication.

Returned data

Name

Type

Example: (value)

Description

Success

Boolean

true

Indicates whether the request was successful. A value of true indicates that the request was successful. A value of false indicates that the request failed.

Code

String

Opreation.Success

The response code.

  • If the value of Success is true, the value of this parameter is Operation.Success.

  • If `Success` is `false`, the `Code` parameter returns one of the error codes listed below.

Message

String

Opreation.Success

A detailed description of the error is returned when Success is false.

RequestId

String

1C0EE50A-B3BB-42FD-AB59-E3FE88976982

The request ID.

Data

String

If the request was successful, the JSON string that is returned contains the UserId parameter.

  • UserId: The value is a string. The unique ID of the user is returned.

If the request failed, no value is returned.

Sample request

Request method: POST

https://idaas-doraemon.aliyuncs.com/?Action=VerifyIdToken
&Version=2021-05-20
&ApplicationExternalId=A0000001
&JwtIdToken=eyJhcHBJ...biI6IjEuMCJ9
&<Common request parameters>

Sample success responses: The JWT token is verified.

{
  "RequestId": "33ED8414-F27C-5CA4-B53F-FDFF61A7C96E",
  "UserId": "123456"
}

Sample error responses: The specified application ID does not exist.

{
  "Success": false,
  "Code": "Operation.Failure.Application.ResourceNotExist",
  "Message": "APIInvokeError.ApplicationDoesNotExist",
  "RequestId": "1C0EE50A-B3BB-42FD-AB59-E3FE88976982"
}

Sample code in Java

The following sample code provides an example on how to obtain a JWT token:

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.idaas_doraemon.model.v20210520.VerifyIdTokenRequest;
import com.aliyuncs.idaas_doraemon.model.v20210520.VerifyIdTokenResponse;
import com.aliyuncs.profile.DefaultProfile;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class IDaaSAuthSample {

    /**
     * Initializes the client using an AccessKey pair.
     *
     * @return Client
     * @throws Exception
     */
    public static IAcsClient createClient() throws Exception {
      // An AccessKey pair of an Alibaba Cloud account has full permissions on all API operations. This poses a high security risk. We strongly recommend that you use a RAM user to make API calls or perform routine O&M. To create a RAM user, log on to the RAM console.
        // This example shows how to store an AccessKey ID and an AccessKey secret in environment variables. You can also store them in a configuration file as needed.
        // Do not hard-code the AccessKey ID and AccessKey secret into your code. Hard-coding the AccessKey pair may cause leakage and threaten the security of your account.
      	String accessKeyId = System.getenv("ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessKeySecret);
        // addEndpoint
        DefaultProfile.addEndpoint("cn-hangzhou",
                "idaas-doraemon",
                "idaas-doraemon.aliyuncs.com");
        // The endpoint to access.
        return new DefaultAcsClient(profile);
    }

    public static void main(String[] args_) throws Exception {
        // Verify the token.
        verifyJwtToken();
    }

    public static void verifyJwtToken() throws Exception {
       IAcsClient client = IDaaSAuthSample.createClient();
       // Verify the JWT token.
       VerifyIdTokenRequest verifyIdTokenRequest = new VerifyIdTokenRequest()
                .setApplicationExternalId("test")
                // Obtain this from the mobile client SDK.
                .setJwtIdToken("eyJhcHBJZCI6ImNvbS5pZHNtYW5hZ2VyLmlkcCIsImFwcE9TIjoiaU9TIiwidGltZXN0YW1wIjoxNjY4NzQwNjIwMDAwLCJkZXZpY2VVbmlxdWVJZCI6IjI0NzA4NUQ3LTFDNTMtNEY2RS1CRDdFLTFGNUU3ODVBNzc1RiIsImJhc2U2NEVuY29kZWRKc29uUGFyYW1zIjoiZTMwPSIsInZlcnNpb24iOiJWMS4yLjAifQ==");
        // After you copy and run the code, print the return value of the API operation.
        try {
            VerifyIdTokenResponse response = client.getAcsResponse(verifyIdTokenRequest);
            System.out.println(JSONObject.toJSON(response).toString());
        } catch (Exception e) {
            // Determine the cause of the exception based on e.getCode().
            System.out.println(e);
        }
    }
}

Maven dependencies of the sample code

  <dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>aliyun-java-sdk-idaas-doraemon</artifactId>
   <version>[1.2.4,1.3.3)</version>
  </dependency>
 <dependency>
   <groupId>com.aliyun</groupId>
   <artifactId>aliyun-java-sdk-core</artifactId>
   <optional>true</optional>
   <version>[4.4.9,5.0.0)</version>
  </dependency>