Configure consumer authentication

更新时间:
复制 MD 格式

The cloud-native gateway supports configuring authentication for routes and authorizing specific consumers to access those routes. This topic describes how to configure consumer authentication.

Important

This topic applies to Standard Edition and Professional Edition of standard cloud-native gateway instances.

Background information

Global authentication is suitable for ToC scenarios such as unified login. Route authentication with consumer authorization is better suited for ToB scenarios such as granting API access to partners.

Comparison item

Global authentication

Route authentication + consumer authorization

Scenarios

ToC scenarios such as unified login authentication.

ToB scenarios such as granting API access to partners.

Key difference

Authentication and authorization are enabled together.

After enabling authentication, you must separately configure authorization.

Configuration entry

Security Management > Global Authentication.

  1. Routes > Policies > Authentication.

  2. Security Management > Consumer Authentication.

Authentication configuration (using JWT as an example)

  1. When creating the configuration, enter global JWKS settings.

  2. Enter the iss and sub fields as criteria to validate JWT tokens.

  1. When creating a consumer configuration, enter the JWKS settings for that consumer.

  2. Enter a consumer ID to identify whether a JWT belongs to this consumer. By default, this uses the payload field uid, but you can customize it.

Authorization configuration

When creating the configuration, enter a list of Domain Name and Path for the blacklist or whitelist.

  • Blacklist: The Domain Name and Path in the list require authentication, and all others can be accessed directly without authentication.

  • Whitelist: The Domain Name and Path entries in the list do not require authentication. All others require authentication.

  1. In the route Policies, enable Authentication for the route.

  2. In Consumer Authentication, associate the route that has authentication enabled to complete 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 target gateway.

  4. In the navigation pane on the left, click Security Management > Consumer Authentication.

  5. Click the Create Consumer button.

  6. Configure the parameters and then click OK.

    The following table describes the parameters.

    configuration item

    Description

    Consumer Name

    Enter a custom name for the consumer.

    Consumer Description

    Describe the consumer.

    Authentication Type

    The authentication methods currently supported by the consumer.

    Key Type

    • Symmetric Key: Generates a default JWKS configuration (unique per consumer) containing the key used to encrypt or decrypt tokens.

    • Asymmetric Key: Requires you to provide a complete JWKS configuration. Use your private key to sign the token. The gateway uses the public key from your JWKS to verify it.

    JWKS

    Set the JWKS configuration. For details about the JWKS specification, see JSON Web Key (JWK).

    JWT Token

    Configure JWT token settings.

    • Type: The token parameter type. Default is Header.

    • Key: The token parameter name.

    • Prefix: The prefix for the token parameter name. By default, tokens are validated in the Authorization Header with the prefix Bearer, for example: Authorization: Bearer token.

    • Enable Passthrough: If selected, the token parameter is passed through to the backend service.

    Consumer Identity in JWT Payload

    Specify the key and value in the JWT payload to identify this consumer. By default, the key is uid and the value is a random string. You can modify these values.

    The JWT token payload should look like this:

    {
      "uid": "11215ac069234abcb8944232b79ae711"
    }

Token generation methods

This section provides a Java example. Users of other languages can find equivalent tools to generate key pairs.

Create a new Maven project and add the following dependency:

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

Generate a token using the default symmetric key

Expand to view 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 {
        // Use the example JWKS shown earlier
        String privateKeyJson = "{\n"
                + "    \"k\": \"VoBG-oyqVoyCr9G56ozmq8n_rlDDyYMQOd_DO4GOkEY\",\n"
                + "    \"kty\": \"oct\",\n"
                + "    \"alg\": \"HS256\",\n"
                + "}";
        JwtClaims claims = new JwtClaims();
        claims.setGeneratedJwtId();
        claims.setIssuedAtToNow();
        // Set expiration time (must be less than 7 days)
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
        // Add custom claims; use String values only
        // Set consumer identifier
        claims.setClaim("uid", "11215ac069234abcb8944232b79ae711");
        JsonWebSignature jws = new JsonWebSignature();
        // Set 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);
    }
}

Code configuration notes:

  • privateKeyJson: This is the JWKS used when creating the consumer. Record it during creation or retrieve it later from the Authentication Configuration section under the Basic Settings tab on the consumer details page.

  • Set the consumer identifier with claims.setClaim("uid", "11215ac069234abcb8944232b79ae711"). This matches the default consumer ID generated in the console but can be customized. View the current value in the Consumer Identifier field under Authentication Configuration on the Basic Settings tab of the consumer details page.

  • Set the encryption algorithm with jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256). This must match the algorithm specified in your JWKS.

    Note

    Supported algorithms include ES256, ES384, ES512, RS256, RS384, RS512, PS256, PS384, PS512, HS256, HS384, HS512, and EdDSA.

    When selecting Symmetric key for Key Type, enter a JWKS with these key properties: "kty":"oct", "k":"VoBG-oyqVoyCr9G56ozmq8n_rlDDyYMQ0d_D04G0kEY", and "alg":"HS256".

    For symmetric encryption, decode the "k" value:

    jws.setKey(new HmacKey(Base64.decode(JsonUtil.parseJson(privateKeyJson).get("k").toString())));

    You can also retrieve the consumer identifier from the Consumer Identifier field under Authentication Configuration on the Basic Settings tab of the consumer details page.

  • Set the expiration time. It must be less than 7 days. Generate a new token after expiration to maintain security.

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

Generate a token using an asymmetric key

Expand to view 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 {
        // Use the example JWKS shown earlier
        String privateKeyJson = "{\n"
                + "    \"k\": \"VoBG-oyqVoyCr9G56ozmq8n_rlDDyYMQOd_DO4GOkEY\",\n"
                + "    \"kty\": \"oct\",\n"
                + "    \"alg\": \"HS256\",\n"
                + "}";
        JwtClaims claims = new JwtClaims();
        claims.setGeneratedJwtId();
        claims.setIssuedAtToNow();
        // Set expiration time (must be less than 7 days)
        NumericDate date = NumericDate.now();
        date.addSeconds(120*60);
        claims.setExpirationTime(date);
        claims.setNotBeforeMinutesInThePast(1);
        // Add custom claims; use String values only
        // Set consumer identifier
        claims.setClaim("uid", "11215ac069234abcb8944232b79ae711");
        JsonWebSignature jws = new JsonWebSignature();
        // Set 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);
    }
}

Code configuration notes:

  • Configure privateKeyJson, consumer identifier, and expiration time as described for symmetric encryption.

  • Set the encryption algorithm with jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256). This must match the algorithm in your JWKS.

    In the console JWKS configuration field, enter a JSON-formatted asymmetric key where the key type (kty) is RSA. Include standard RSA parameters such as p, q, d, and e, with e set to AQAB. In the JWT Token configuration section, set Type to HEADER, Key to Authorization, Prefix to Bearer, and check Pass-through.

    For asymmetric encryption, sign the token with your private key:

    ...
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyJson)).getPrivateKey();
        jws.setKey(privateKey);
    ...
  • Based on your business needs, you can add custom parameters to the PAYLOAD in JWKS.

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 ID of the gateway.

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

  5. In the Actions column for the target route, click Policies.

  6. On the Policies tab, click Authentication. After configuring, click Save.

    Parameter

    Description

    Authentication Method

    The authentication method used for this route.

    Enabling Status

    When enabled, authentication and authorization take effect.

Grant access to 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 ID of the gateway.

  4. In the navigation pane on the left, click Security Management > Consumer Authentication.

  5. In the Actions column for the target consumer, click Authorization.

  6. On the Consumer Authorization tab, click Associate Route, select the routes to authorize for this consumer, and then click OK.