All Products
Search
Document Center

Microservices Engine:Configure consumer authorization

Last Updated:Apr 10, 2024

In Microservices Engine (MSE) cloud-native gateways, you can configure an authentication rule for a route to allow only access from authenticated consumers. This topic describes how to configure consumer authorization.

Background information

Global authentication is suitable for To Consumer (ToC) scenarios, such as centralized logon authentication. Route authentication and consumer authorization are suitable for To Business (ToB) scenarios, such as granting permissions on API operations to partners.

Item

Global authentication

Route authentication and consumer authorization

Scenario

ToC scenarios, such as centralized logon authentication.

ToB scenarios, such as granting permissions on API operations to partners.

Core difference

Authorization is also enabled when you enable authentication.

You must configure authorization settings after you enable authentication.

Entry point

Security Management > Global Authentication

  1. Routes > Policies > Authentication

  2. Security Management > Consumer Authentication

Configuration of authentication based on JSON Web Token (JWT)

  1. When you create an authentication rule, enter the global JWKS configuration.

  2. Specify the Issue and Sub fields that are used to verify the JWT.

  1. When you create a consumer, enter the JWKS configuration of the consumer.

  2. In the Consumer Identity field in the JWT Payload section, specify the key-value pair that is used to identify the consumer. By default, the value of uid in payload is used. You can specify a key-value pair based on your business requirements.

Authorization configuration

When you create an authorization rule, select Whitelist or Blacklist and specify the Domain Name and Path fields.

  • Blacklist: Consumers whose Domain Name and Path are included in the blacklist must be authenticated. Other consumers do not need to be authenticated.

  • Whitelist: Consumers whose Domain Name and Path are included in the whitelist do not need to be authenticated. Other consumers must be authenticated.

  1. On the Policies page, enable Authentication for the route.

  2. On the Consumer Authentication page, associate the route for which authentication is enabled with the consumer to complete the authorization.

Create a consumer

  1. Log on to the MSE console. In the top navigation bar, select a region.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways.

  3. On the Gateways page, click the name of the gateway.

  4. In the left-side navigation pane, choose Security Management > Consumer Authentication.

  5. Click Create Consumer.

  6. Configure the parameters and click OK.

    创建消费者.png

    The following table describes the parameters.

    Parameter

    Description

    Consumer Name

    The name of the consumer.

    Consumer Description

    The description of the consumer.

    Authentication Type

    The authentication method that is supported by the consumer.

    Key Type

    • Symmetric Key: A default JWKS that varies based on the consumer is generated. The default JWKS contains the key that is used to encrypt or decrypt the token.

    • Asymmetric Key: You must enter the complete JWKS configuration. The token is encrypted by using a private key. The gateway performs decryption based on the public key in JWKS.

    JWKS

    Enter the JWKS configuration. For more information about JWKS specifications, see JSON Web Key (JWK).

    JWT Token

    Configure the JWT token.

    • Type: the type of the token. The default value is HEADER.

    • Key: the name of the token.

    • Prefix: the prefix of the token. Configure the required parameters to validate the token. By default, the token contains the Bearer prefix and is stored in the Authorization header. Example: Authorization: Bearer <token>.

    • Enable Passthrough: If you select this option, the token is passed to the backend service.

    Consumer Identity in JWT Payload

    The key and value in the JWT payload that are used to identify the consumer. By default, the key is uid, and the value is a random string. You can change the value based on your business requirement.

    The following code is the payload in the JWT token if a consumer is created based on the configurations in the preceding figure.

    {
      "uid": "11215ac069234abcb8944232b79ae711"
    }

Token generation methods

This section provides examples on generating a token in Java. In other programming languages, you can use related tools to generate a key pair.

Create a Maven project and add the following dependency to the project:

<dependency>
    <groupId>org.bitbucket.b_c</groupId>
    <artifactId>jose4j</artifactId>
    <version>0.7.0</version>
</dependency>

Use the default symmetric key to generate a token

Show code

package org.example;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;

import org.jose4j.base64url.Base64;
import org.jose4j.json.JsonUtil;
import org.jose4j.jwk.OctJwkGenerator;
import org.jose4j.jwk.OctetSequenceJsonWebKey;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.keys.HmacKey;
import org.jose4j.lang.JoseException;
import sun.lwawt.macosx.CSystemTray;

public class Main {
    public static void main(String[] args) throws JoseException, UnsupportedEncodingException {
        // The preceding example is used.
        String privateKeyJson = "{\n"
                + "    \"k\": \"VoBG-oyqVoyCr9G56ozmq8n_rlDDyYMQOd_DO4GOkEY\",\n"
                + "    \"kty\": \"oct\",\n"
                + "    \"alg\": \"HS256\",\n"
                + "}";
        JwtClaims claims = new JwtClaims();
        claims.setGeneratedJwtId();
        claims.setIssuedAtToNow();
        // Specify the expiration time, which is less than seven days.
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
        // Add custom parameters. All parameter values must be of the STRING type.
        // Configure the consumer ID.
        claims.setClaim("uid", "11215ac069234abcb8944232b79ae711");
        JsonWebSignature jws = new JsonWebSignature();
        // Specify the encryption algorithm.
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(new HmacKey(Base64.decode(JsonUtil.parseJson(privateKeyJson).get("k").toString())));
        jws.setPayload(claims.toJson());
        String jwtResult = jws.getCompactSerialization();
        System.out.println("Generate Json Web token , result is \n " + jwtResult);
    }
}

Configurations in the code:

  • The privateKeyJson configuration specifies the JWKS that is used when you create a consumer. You can record the JWKS when you create a consumer or obtain the JWKS from the basic configuration page for the consumer after you create the consumer.

    消费者.png

  • Configure the consumer ID. The claims.setClaim("uid", "11215ac069234abcb8944232b79ae711") configuration specifies the consumer ID. It is automatically generated by the console when you create the consumer. You can modify the consumer ID based on the logic.

    消费者标识.png

    You can also obtain the consumer ID on the basic configuration page for the consumer after you create the consumer.获取消费者标识.png

  • Configure the encryption algorithm. The jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256) configuration specifies the encryption algorithm, which must be consistent with JWKS.

    Note

    The following encryption algorithms are supported: ES256, ES384, ES512, RS256, RS384, RS512, PS256, PS384, PS512, HS256, HS384, HS512, and EdDSA.

    加密算法.png

    When you use symmetric encryption, you must decode "k".

    jws.setKey(new HmacKey(Base64.decode(JsonUtil.parseJson(privateKeyJson).get("k").toString())));
  • Configure the expiration time. The expiration time must be less than seven days. After the expiration time is reached, we recommend that you generate a new token to ensure security.

    ...
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
    ...
  • You can add custom parameters to the JWKS PAYLOAD based on your business requirements.

Use an asymmetric key to generate a token

Show code

package org.example;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;

import org.jose4j.base64url.Base64;
import org.jose4j.json.JsonUtil;
import org.jose4j.jwk.OctJwkGenerator;
import org.jose4j.jwk.OctetSequenceJsonWebKey;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.keys.HmacKey;
import org.jose4j.lang.JoseException;
import sun.lwawt.macosx.CSystemTray;

public class Main {
    public static void main(String[] args) throws JoseException, UnsupportedEncodingException {
        // The preceding example is used.
        String privateKeyJson = "{\n"
                + "    \"k\": \"VoBG-oyqVoyCr9G56ozmq8n_rlDDyYMQOd_DO4GOkEY\",\n"
                + "    \"kty\": \"oct\",\n"
                + "    \"alg\": \"HS256\",\n"
                + "}";
        JwtClaims claims = new JwtClaims();
        claims.setGeneratedJwtId();
        claims.setIssuedAtToNow();
        // Specify the expiration time, which is less than seven days.
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
        // Add custom parameters. All parameter values must be of the STRING type.
        // Configure the consumer ID.
        claims.setClaim("uid", "11215ac069234abcb8944232b79ae711");
        JsonWebSignature jws = new JsonWebSignature();
        // Configure the encryption algorithm.
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(new HmacKey(Base64.decode(JsonUtil.parseJson(privateKeyJson).get("k").toString())));
        jws.setPayload(claims.toJson());
        String jwtResult = jws.getCompactSerialization();
        System.out.println("Generate Json Web token , result is \n " + jwtResult);
    }
}

Configurations in the code:

  • Configure the privateKeyJson parameter, consumer ID, and expiration time the same as those when you use the symmetric encryption algorithm.

  • The jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256) configuration specifies the encryption algorithm. The encryption algorithm must be consistent with JWKS.

    If an asymmetric encryption algorithm is used, the private key is required for encryption.

    ...
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyJson)).getPrivateKey();
        jws.setKey(privateKey);
    ...
  • You can add custom parameters to the JWKS PAYLOAD based on your business requirements.

Enable route authentication

  1. Log on to the MSE console. In the top navigation bar, select a region.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways.

  3. On the Gateways page, click the name of the gateway.

  4. In the left-side navigation pane, click Routes, and click the Routes tab.

  5. Find the desired route, and click Policies in the Actions column.

  6. On the Policies page, click the Authentication tab. Then, configure the parameters, and click Save.

    Parameter

    Description

    Authentication Type

    The method that is used to authenticate a consumer before the consumer can access the route.

    Enabled

    Specifies whether to enable authentication. After you turn on the switch, authentication takes effect.

Authorize the consumer to access a route

  1. Log on to the MSE console. In the top navigation bar, select a region.

  2. In the left-side navigation pane, choose Cloud-native Gateway > Gateways.

  3. On the Gateways page, click the name of the gateway.

  4. In the left-side navigation pane, choose Security Management > Consumer Authentication.

  5. Find the desired consumer and click Authorization in the Actions column.

  6. On the Consumer Authorization tab, click Associate Route, select the route on which you want the consumer to have access permissions, and then click OK.