API Gateway allows you to implement user authorization and authentication for an API operation based on the OpenID Connect authentication layer and the backend service of the API operation. This allows you to customize security configurations based on your own business requirements.

1. Introduction to OpenID Connect

OpenID Connect, launched in 2014, is a simple authentication layer on top of OAuth 2.0 and implements user authorization and authentication in an interoperable manner. OpenID Connect uses REST and JSON messages to implement user authorization and authentication, which makes it easier for developers to integrate than other identity authentication protocols. OpenID Connect allows clients to verify the identity of a user based on the authentication that is performed by an authorization server, as well as to obtain basic profile information about the user in an interoperable and REST-like manner. OpenID Connect allows a range of kinds of clients, including web-based, mobile, and JavaScript clients, to request and receive information about authenticated sessions and users. The specification suite is extensible and supports optional features such as encryption of identity data, discovery of OpenID providers, and session management.

1.1 Roles in OpenID Connect authentication

  1. Client: A user uses a client to access a business service.
  2. Authorization server: an OpenID provider, generally an OpenID authorization server. An OpenID authorization server issues ID tokens to clients, so that the clients can access a specific business service.
  3. Business server: provides specific business services, such as user information query.
  4. User: the owner of a client.

1.2 How it works

  1. The client sends an authentication request to the authorization server.
  2. Optional. The authorization server requires the user to confirm the authorization operation on the client.
  3. The authorization server validates the authentication request and sends an ID token to the client.
  4. The client constructs a business request that includes the ID token and sends the business request to the business server.
  5. The business server verifies whether the ID token is valid and, if so, returns a business response to the client.

Step 2 is optional. If the request in step 1 contains a username and a password, the authorization server verifies whether the username and password are valid and, if so, sends an ID token to the client. Step 2 is skipped. In this way, the entire process is more efficient. Step 2 is skipped in OpenID Connect authentication that is supported by API Gateway. For more information, see section 2.

1.3 JWT standard

Each ID token that is issued by the authorization server must strictly abide by the JSON Web Token (JWT) standard. The following standard fields, also known as claims, can be used in a JWT claim set:

  1. iss: required. Stands for Issuer Identifier. The unique identifier of an authorization server. The value of this claim is an HTTPS URL that is case-sensitive and does not include query parameters or fragments.
  2. sub: required. Stands for Subject Identifier. The identifier of a user. The value of this claim is unique under the same authorization server. This claim can contain a maximum of 255 ASCII characters that are case-sensitive.
  3. aud: required. Stands for Audience(s). The recipient that the ID token is intended for. This claim must contain the ID of a client. The value of this claim is a case-sensitive string array.
  4. exp: required. Stands for Expiration Time. The validity period of the ID token, after which the ID token cannot be accepted for processing.
  5. iat: required. Stands for Issued At Time. The time point at which the ID token was issued.
  6. auth_time: Stands for Authentication Time. The time point at which the user completed the authentication.
  7. nonce: a random string that is generated by a client, sent as a query string parameter in an authentication request, and included in an ID token response. This claim is used to mitigate replay attacks and correlate the ID token response with the initial authentication request. After a client sends an authentication request that includes a nonce claim and then receives an ID token response, the client must validate the nonce claim in the response. The nonce claim in the response must contain the exact same value that was sent in the request. If not, authentication will be rejected.
  8. acr: optional. Stands for Authentication Context Class Reference. This claim describes a set of authentication methods that are equivalent in a given context.
  9. amr: optional. Stands for Authentication Methods References. The supported authentication methods.
  10. azp: optional. Stands for Authorized Party. This claim is used together with the aud claim. This claim is used only when the party to be authorized is different from the recipient that is specified by the aud claim.

The following code snippet shows a typical example of an ID token:

{
	"iss": "https://1.2.3.4:8443/auth/realms/kubernetes",
	"sub": "547cea22-fc8a-4315-bdf2-6c92592a6e7c",
	"aud": "kubernetes",
	"exp": 1525158711,
	"iat": 1525158411,
	"auth_time": 0,
	"nonce": "n-0S6_WzA2Mj",
	"acr": "1",
	"azp": "kubernetes",
	"nbf": 0,
	"typ": "ID",
	"session_state": "150df80e-92a1-4b0c-a5c5-8c858eb5a848",
	"userId": "123456",
	"preferred_username": "theone",
	"given_name": "the",
	"family_name": "one",
	"email": "theone@mycorp.com"
}

For more information about ID tokens, see OpenID Connect Core 1.0.

2. Implementation of OpenID Connect authentication by using API Gateway

API Gateway allows you to implement OpenID Connect authentication to authorize users to call an API operation. In OpenID Connect authentication, API Gateway checks the validity of the ID token in each API request. If the ID token is invalid, API Gateway rejects the API request.

2.1 Preparations

To implement OpenID Connect authentication, you must complete the following configurations in the API Gateway console:

1. Create an authorization API operation and configure a public key for this API operation.

2. Set the Security Certification parameter to OpenID Connect or OpenID Connect & Alibaba Cloud APP for each business API operation.

For more information, see section 3.

2.2 Authentication process

The preceding figure shows how OpenID Connect authentication works in API Gateway, including the following steps:

1. The client sends an authentication request to API Gateway. Generally, the username and password of the user are included in the request.

2. API Gateway forwards the authentication request to the backend service.

3. The backend service reads and verifies the authentication information, such as the username and password, in the authentication request. After the request passes the verification, the backend service uses the private key to generate a standard ID token and returns an ID token response to API Gateway.

4. API Gateway forwards the ID token response to the client. The client needs to cache the ID token locally.

5. The client sends a business request to API Gateway. The ID token is included in the business request.

6. API Gateway uses the public key that is configured for the authorization API operation to verify the ID token in the business request. If the request passes the verification, API Gateway directly forwards the business request to the backend service.

7. The backend service handles the business request and sends a business response to API Gateway.

8. API Gateway forwards the business response to the client.

In the authentication process, API Gateway integrates itself, the backend service, and OpenID Connect authentication to implement user authorization.

2.3 Authorization scope and validity period

By default, each ID token can be used to access all API operations that use OpenID Connect authentication in the same API group. If you need finer-grained permission management, configure that the backend service checks the ID token in each API request to see if the ID token has the permission to call the API operation. As for the validity of an ID token, API Gateway checks the exp claim in the ID token in each API request. If the ID token has expired, API Gateway considers the ID token invalid and rejects the API request. You must set a validity period for ID tokens. The validity period must be less than seven days.

3. Configure OpenID Connect authentication for an API operation

This section describes how to configure OpenID Connect authentication for an API operation. Perform the following steps:

1. Generate a key pair that consists of a public key and a private key.

2. Create an authorization API operation and configure the public key for the API operation.

3. Set the Security Certification parameter to OpenID Connect or OpenID Connect & Alibaba Cloud APP for each business API operation.

3.1 Generate a public key and a private key

You can go to https://mkjwk.org to generate a public key and a private key that will be used to generate and validate ID tokens. API Gateway supports SHA-256 with RSA-2048 encryption for key pairs.

The public key will be used to configure the authorization API operation in section 3.2.1. The following code snippet shows an example of a public key:

{
  "kty": "RSA",
  "e": "AQAB",
  "kid": "uniq_key",
  "alg": "RS256",
  "n": "gbnCVY4XxM-MB1mseAJnIItognv3LRuHkVv5W-gF-yvXnYfi8t-L33oF73i4eyE9i4uSElP-CCoSbyJUJhhNSS7_njDp6Ex3WNq0KimRSmXanD5453CFBrgxJlai4aaZxPYsIdjqiVijAris40gRVZQ7aMtDc6Rmu1IS3564dYJ0YR9GA8tZPvuX8ESHnSXgQLM8y6BBLpoojSKajApOK1QW6RieQZZcMIuMjOoJb9NWHqSDFm7PXYeQWxpH_HfN1wMPo7tln5vWbi-vFIHJanWF1syZ9XR0yba53YmMBj7-YDuxF3_sTK-9I8upWGEC9M16Qn-C7eHcDMLZ8XoSUw"
}

The private key will be used to write code for ID token generation in section 4. The following code snippet shows an example of a private key:

{
  "kty": "RSA",
  "d": "HSmya2NXKpJx61EYeZ4oquNMKlFN_uD6eA4SH7woZA-2GB7tQSZKHoIjBXPBHUUavd0xiFdDe3hhzoQMIMhDz5j2NAzQ-Lz_84SvDe9sTypYm9lbesQL07firLi7Qzkdxm6E-1L1Xs0DUGBN1YZlBzUcqfFQB5ZE1gWcYpMe6qOHkJWkb5GaiZm_x3D-fUYO5VV7t0G-NtrF5FAs06qVW7fgMqeOi6l9_-Nyldc1XKAOrmqzOu5GqgLMkyN76I_FYikNQiTdvReR5lg6YYULH0rPcKsDBllalAOz1HZQhYK7xC9AyYN2iEyQwlQWwepirs1taUTsH6YoegeK2sazwQ",
  "e": "AQAB",
  "kid": "uniq_key",
  "alg": "RS256",
  "n": "gbnCVY4XxM-MB1mseAJnIItognv3LRuHkVv5W-gF-yvXnYfi8t-L33oF73i4eyE9i4uSElP-CCoSbyJUJhhNSS7_njDp6Ex3WNq0KimRSmXanD5453CFBrgxJlai4aaZxPYsIdjqiVijAris40gRVZQ7aMtDc6Rmu1IS3564dYJ0YR9GA8tZPvuX8ESHnSXgQLM8y6BBLpoojSKajApOK1QW6RieQZZcMIuMjOoJb9NWHqSDFm7PXYeQWxpH_HfN1wMPo7tln5vWbi-vFIHJanWF1syZ9XR0yba53YmMBj7-YDuxF3_sTK-9I8upWGEC9M16Qn-C7eHcDMLZ8XoSUw"
}

3.2 Create an authorization API operation and a business API operation

3.2.1 Create an authorization API operation

The following figure shows the page where you can configure basic information for the authorization API operation. You can complete other configurations as needed.

When you configure basic information for the authorization API operation, take note of the following parameters:

  1. Security Certification: Set this parameter to OpenID Connect or OpenID Connect & Alibaba Cloud APP. If you select OpenID Connect & Alibaba Cloud APP, both the ID token and the encrypted signature in each API request will be authenticated by the backend service of the API operation to be called. For information about how to calculate a signature, see Request signature.
  2. OpenID Connect: Set this parameter to Authorization API.
  3. KeyId: Enter a name for the public key. The name must be unique within the API group to which the authorization API operation belongs. We recommend that the name contain letters and digits.
  4. Public key: Enter the public key that you generated. You must enter the entire JSON string array of the public key.

3.2.2 Create a business API operation

The following figure shows the page where you can configure basic information for the business API operation. You can complete other configurations as needed.
  1. Security Certification: Set this parameter to OpenID Connect or OpenID Connect & Alibaba Cloud APP. If you select OpenID Connect & Alibaba Cloud APP, both the ID token and the encrypted signature in each API request will be authenticated by the backend service of the API operation to be called. For information about how to calculate a signature, see Request signature.
  2. OpenID Connect: Set this parameter to Business API.
  3. Token Parameter Name: Enter a name for the ID token, for example, idToken. The name represents the ID token in each API request.

3.3 Create a plug-in of the JWT Authorization type

You can also create a plug-in of the JWT Authorization type to implement OpenID Connect authentication. For more information, see JWT authentication.

4. Configure the logic of issuing ID tokens for the backend service


import java.security.PrivateKey; 
import org.jose4j.json.JsonUtil;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.lang.JoseException;


public class GenerateJwtDemo {
    public static void main(String[] args) throws JoseException  {
		  // Use the value of the KeyId parameter that you specified when you configured basic information for the authorization API operation.
        String keyId = "uniq_key";
		  // Use the key pair that was generated in section 3.1.
        String privateKeyJson = "{\n"
            + "  \"kty\": \"RSA\",\n"
            + "  \"d\": "
            +
            "\"O9MJSOgcjjiVMNJ4jmBAh0mRHF_TlaVva70Imghtlgwxl8BLfcf1S8ueN1PD7xV6Cnq8YenSKsfiNOhC6yZ_fjW1syn5raWfj68eR7cjHWjLOvKjwVY33GBPNOvspNhVAFzeqfWneRTBbga53Agb6jjN0SUcZdJgnelzz5JNdOGaLzhacjH6YPJKpbuzCQYPkWtoZHDqWTzCSb4mJ3n0NRTsWy7Pm8LwG_Fd3pACl7JIY38IanPQDLoighFfo-Lriv5z3IdlhwbPnx0tk9sBwQBTRdZ8JkqqYkxUiB06phwr7mAnKEpQJ6HvhZBQ1cCnYZ_nIlrX9-I7qomrlE1UoQ\",\n"
            + "  \"e\": \"AQAB\",\n"
            + "  \"kid\": \"myJwtKey\",\n"
            + "  \"alg\": \"RS256\",\n"
            + "  \"n\": \"vCuB8MgwPZfziMSytEbBoOEwxsG7XI3MaVMoocziP4SjzU4IuWuE_DodbOHQwb_thUru57_Efe"
            +
            "--sfATHEa0Odv5ny3QbByqsvjyeHk6ZE4mSAV9BsHYa6GWAgEZtnDceeeDc0y76utXK2XHhC1Pysi2KG8KAzqDa099Yh7s31AyoueoMnrYTmWfEyDsQL_OAIiwgXakkS5U8QyXmWicCwXntDzkIMh8MjfPskesyli0XQD1AmCXVV3h2Opm1Amx0ggSOOiINUR5YRD6mKo49_cN-nrJWjtwSouqDdxHYP-4c7epuTcdS6kQHiQERBd1ejdpAxV4c0t0FHF7MOy9kw\"\n"
            + "}";

        JwtClaims claims = new JwtClaims();
        claims.setGeneratedJwtId();
        claims.setIssuedAtToNow();
        // The validity period is required and must be less than seven days.
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
        claims.setSubject("YOUR_SUBJECT");
        claims.setAudience("YOUR_AUDIENCE");
        // Add custom parameters. All parameter values must be of the STRING type.
        claims.setClaim("userId", "1213234");
        claims.setClaim("email", "userEmail@youapp.com");

        JsonWebSignature jws = new JsonWebSignature();
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
		  // The KeyIdHeaderValue parameter is required.
        jws.setKeyIdHeaderValue(keyId);
        jws.setPayload(claims.toJson());
        PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyJson)).getPrivateKey();
        jws.setKey(privateKey);
        String jwtResult = jws.getCompactSerialization();
        System.out.println("Generate Json Web token , result is " + jwtResult);
    }
}
			

The preceding code snippet shows how to generate an ID token by using Java code. Take note of the following items:

1. The ID of the key must be unique within API Gateway. You must keep this value consistent in relevant steps:

- In section 3.1, enter a value in the Key ID field when you generate a key pair on the website.

- In section 3.2.1, specify the KeyId parameter for the authorization API operation.

- Specify the keyId parameter in the preceding code.

2. The KeyIdHeaderValue parameter must be specified for the JsonWebSignature object.

3. The privateKeyJson parameter must be set to the JSON strings in the Keypair field in section 3.1.

4. The validity period is required and must be less than seven days.

5. If you need to add custom parameters, make sure that all parameter values are of the STRING type.

5. FAQ

5.1 How does encrypted signature authentication work?

If you set the Security Certification parameter to OpenID Connect & Alibaba Cloud APP when you configure basic information for an API operation, each request for the API operation must include a signature that is encrypted by using an AccessKey. For more information, see Request signature.

5.2 Can I configure OpenID Connect authentication by importing an OpenAPI specification file?

No, you cannot configure OpenID Connect authentication by importing an OpenAPI specification file.

5.3 How do I understand error codes and messages in API Gateway?

HTTP status code Error message Description
401 OpenId Connect Verify Fail, IdToken Not Exist The error message returned because the request for the business API operation does not include an ID token.
401 234, JWS set idToken exception The error message returned because an exception occurred when the ID token was being parsed.
401 234, Not found by keyId The error message returned because no public key was found based on the KeyId parameter in the ID token.
401 235, JWS set Public-Key exception The error message returned because the public key that is found based on the KeyId parameter in the ID token is unavailable.
401 237, Verify signature failed The error message returned because the encrypted signature in the API request failed the authentication.
401 245, IdToken is out of scope The error message returned because the ID token in the request is not authorized to be used to call API operations in the current API group.
401 238, JWS get payload exception The error message returned because the payload in the ID token in the API request cannot be found.
401 239, Parse payload to JwtClaims exception The error message returned because an error occurred when the payload was being converted to JWT claims.
401 239, idToken expired The error message returned because the ID token in the API request has expired.
401 Invalid OpenId Connect Config The error message returned because OpenID Connect authentication is not configured for the API operation to be called.