# \[API] Basic Authentication (ok)

Đọc thêm hướng dẫn ở <https://github.com/WP-API/Basic-Auth>

Add Basic Authentication to a Service or a Route with username and password protection. The plugin will check for valid credentials in the `Proxy-Authorization` and `Authorization` header (in this order).**Note:** The functionality of this plugin as bundled with versions of Kong prior to 0.14.0 and Kong Enterprise prior to 0.34 differs from what is documented herein. Refer to the [CHANGELOG](https://github.com/Kong/kong/blob/master/CHANGELOG.md) for details.

### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#configuration)Configuration Reference <a href="#configuration" id="configuration"></a>

You can configure this plugin using the [Kong Admin API](https://docs.konghq.com/latest/admin-api/#plugin-object) or through [declarative configuration](https://docs.konghq.com/deck), which involves directly editing the Kong configuration file.

This plugin is compatible with requests with the following protocols:

* `http`
* `https`
* `grpc`
* `grpcs`

This plugin is **partially compatible** with DB-less mode.

In DB-less mode, Kong does not have an Admin API. If using this mode, configure the plugin using declarative configuration.

Consumers and Credentials can be created with declarative configuration.

Admin API endpoints which do POST, PUT, PATCH or DELETE on Credentials are not available on DB-less mode.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#enabling-the-plugin-on-a-service)Enabling the plugin on a Service <a href="#enabling-the-plugin-on-a-service" id="enabling-the-plugin-on-a-service"></a>

Kong Admin APIKubernetesDeclarative (YAML)

For example, configure this plugin on a [Service](https://docs.konghq.com/latest/admin-api/#service-object) by making the following request:

```
$ curl -X POST http://<admin-hostname>:8001/services/<service>/plugins \
    --data "name=basic-auth"  \
    --data "config.hide_credentials=true"
```

`<service>` is the `id` or `name` of the Service that this plugin configuration will target.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#enabling-the-plugin-on-a-route)Enabling the plugin on a Route <a href="#enabling-the-plugin-on-a-route" id="enabling-the-plugin-on-a-route"></a>

Kong Admin APIKubernetesDeclarative (YAML)

For example, configure this plugin on a [Route](https://docs.konghq.com/latest/admin-api/#route-object) with:

```
$ curl -X POST http://<admin-hostname>:8001/routes/<route>/plugins \
    --data "name=basic-auth"  \
    --data "config.hide_credentials=true"
```

`<route>` is the `id` or `name` of the Route that this plugin configuration will target.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#enabling-the-plugin-globally)Enabling the plugin globally <a href="#enabling-the-plugin-globally" id="enabling-the-plugin-globally"></a>

A plugin which is not associated to any Service, Route, or Consumer is considered *global*, and will be run on every request. Read the [Plugin Reference](https://docs.konghq.com/latest/admin-api/#add-plugin) and the [Plugin Precedence](https://docs.konghq.com/latest/admin-api/#precedence) sections for more information.Kong Admin APIKubernetesDeclarative (YAML)

For example, configure this plugin globally with:

```
$ curl -X POST http://<admin-hostname>:8001/plugins/ \
    --data "name=basic-auth"  \
    --data "config.hide_credentials=true"
```

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#parameters)Parameters <a href="#parameters" id="parameters"></a>

Here's a list of all the parameters which can be used in this plugin's configuration:

| Form Parameter                                                                                                                                       | Description                                                                                                                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p><code>name</code><br><br><strong>Type:</strong> string</p>                                                                                        | The name of the plugin to use, in this case `basic-auth`.                                                                                                                                                                                                                                                         |
| <p><code>service.id</code><br><br><strong>Type:</strong> string</p>                                                                                  | The ID of the Service the plugin targets.                                                                                                                                                                                                                                                                         |
| <p><code>route.id</code><br><br><strong>Type:</strong> string</p>                                                                                    | The ID of the Route the plugin targets.                                                                                                                                                                                                                                                                           |
| <p><code>enabled</code><br><br><strong>Type:</strong> boolean<br><br><strong>Default value:</strong> <code>true</code></p>                           | Whether this plugin will be applied.                                                                                                                                                                                                                                                                              |
| <p><code>config.hide\_credentials</code><br><em>optional</em><br><br><strong>Type:</strong> boolean<br><br><strong>Default value:</strong> false</p> | An optional boolean value telling the plugin to show or hide the credential from the upstream service. If `true`, the plugin will strip the credential from the request (i.e. the `Authorization` header) before proxying it.                                                                                     |
| <p><code>config.anonymous</code><br><em>optional</em><br><br><strong>Type:</strong> string</p>                                                       | An optional string (consumer uuid) value to use as an “anonymous” consumer if authentication fails. If empty (default), the request will fail with an authentication failure `4xx`. Please note that this value must refer to the Consumer `id` attribute which is internal to Kong, and **not** its `custom_id`. |

Once applied, any user with a valid credential can access the Service. To restrict usage to only some of the authenticated users, also add the [ACL](https://docs.konghq.com/plugins/acl/) plugin (not covered here) and create allowed or denied groups of users.

### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#usage)Usage <a href="#usage" id="usage"></a>

In order to use the plugin, you first need to create a Consumer to associate one or more credentials to. The Consumer represents a developer or an application consuming the upstream service.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#create-a-consumer)Create a Consumer <a href="#create-a-consumer" id="create-a-consumer"></a>

You need to associate a credential to an existing [Consumer](https://docs.konghq.com/latest/admin-api/#consumer-object) object. A Consumer can have many credentials.

**With a Database**

To create a Consumer, you can execute the following request:

```
curl -d "username=user123&custom_id=SOME_CUSTOM_ID" http://kong:8001/consumers/
```

**Without a Database**

Your declarative configuration file will need to have one or more Consumers. You can create them on the `consumers:` yaml section:

```
consumers:
- username: user123
  custom_id: SOME_CUSTOM_ID
```

In both cases, the parameters are as described below:

| parameter                                                | description                                                                                                          |
| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| <p><code>username</code><br><em>semi-optional</em></p>   | The username of the consumer. Either this field or `custom_id` must be specified.                                    |
| <p><code>custom\_id</code><br><em>semi-optional</em></p> | A custom identifier used to map the consumer to another database. Either this field or `username` must be specified. |

If you are also using the [ACL](https://docs.konghq.com/plugins/acl/) plugin and allow lists with this service, you must add the new consumer to the allowed group. See [ACL: Associating Consumers](https://docs.konghq.com/plugins/acl/#associating-consumers) for details.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#create-a-credential)Create a Credential <a href="#create-a-credential" id="create-a-credential"></a>

**With a Database**

You can provision new username/password credentials by making the following HTTP request:

```
$ curl -X POST http://kong:8001/consumers/{consumer}/basic-auth \
    --data "username=Aladdin" \
    --data "password=OpenSesame"
```

**Without a Database**

You can add credentials on your declarative config file on the `basicauth_credentials` yaml entry:

```
basicauth_credentials:
- consumer: {consumer}
  username: Aladdin
  password: OpenSesame
```

In both cases, the fields / parameters work as described below:

| field/parameter                                   | description                                                                                                                                          |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{consumer}`                                      | The `id` or `username` property of the [Consumer](https://docs.konghq.com/latest/admin-api/#consumer-object) entity to associate the credentials to. |
| `username`                                        | The username to use in the Basic Authentication                                                                                                      |
| <p><code>password</code><br><em>optional</em></p> | The password to use in the Basic Authentication                                                                                                      |

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#using-the-credential)Using the Credential <a href="#using-the-credential" id="using-the-credential"></a>

The authorization header must be base64 encoded. For example, if the credential uses `Aladdin` as the username and `OpenSesame` as the password, then the field’s value is the base64-encoding of `Aladdin:OpenSesame`, or `QWxhZGRpbjpPcGVuU2VzYW1l`.

Then the `Authorization` (or `Proxy-Authorization`) header must appear as:

```
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
```

Simply make a request with the header:

```
$ curl http://kong:8000/{path matching a configured Route} \
    -H 'Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l'
```

gRPC clients are supported too:

```
$ grpcurl -H 'Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l' ...
```

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#upstream-headers)Upstream Headers <a href="#upstream-headers" id="upstream-headers"></a>

When a client has been authenticated, the plugin will append some headers to the request before proxying it to the upstream service, so that you can identify the Consumer in your code:

* `X-Consumer-ID`, the ID of the Consumer on Kong
* `X-Consumer-Custom-ID`, the `custom_id` of the Consumer (if set)
* `X-Consumer-Username`, the `username` of the Consumer (if set)
* `X-Credential-Identifier`, the identifier of the Credential (only if the consumer is not the ‘anonymous’ consumer)
* `X-Anonymous-Consumer`, will be set to `true` when authentication failed, and the ‘anonymous’ consumer was set instead.

You can use this information on your side to implement additional logic. You can use the `X-Consumer-ID` value to query the Kong Admin API and retrieve more information about the Consumer.**Note:**\`X-Credential-Username\` was deprecated in favor of \`X-Credential-Identifier\` in Kong 2.1.

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#paginate-through-the-basic-auth-credentials)Paginate through the basic-auth Credentials <a href="#paginate-through-the-basic-auth-credentials" id="paginate-through-the-basic-auth-credentials"></a>

**Note:** This endpoint was introduced in Kong 0.11.2.

You can paginate through the basic-auth Credentials for all Consumers using the following request:

```
$ curl -X GET http://kong:8001/basic-auths

{
    "total": 3,
    "data": [
        {
            "created_at": 1511379926000,
            "id": "805520f6-842b-419f-8a12-d1de8a30b29f",
            "password": "37b1af03d3860acf40bd9c681aa3ef3f543e49fe",
            "username": "baz",
            "consumer": { "id": "5e52251c-54b9-4c10-9605-b9b499aedb47" }
        },
        {
            "created_at": 1511379863000,
            "id": "8edfe5c7-3151-4d92-971f-3faa5e6c5d7e",
            "password": "451b06c564a06ce60874d0ea2f542fa8ed26317e",
            "username": "foo",
            "consumer": { "id": "89a41fef-3b40-4bb0-b5af-33da57a7ffcf" }
        },
        {
            "created_at": 1511379877000,
            "id": "f11cb0ea-eacf-4a6b-baea-a0e0b519a990",
            "password": "451b06c564a06ce60874d0ea2f542fa8ed26317e",
            "username": "foobar",
            "consumer": { "id": "89a41fef-3b40-4bb0-b5af-33da57a7ffcf" }
        }
    ]
}
```

You can filter the list by consumer by using this other path:

```
$ curl -X GET http://kong:8001/consumers/{username or id}/basic-auth

{
    "total": 1,
    "data": [
        {
            "created_at": 1511379863000,
            "id": "8edfe5c7-3151-4d92-971f-3faa5e6c5d7e",
            "password": "451b06c564a06ce60874d0ea2f542fa8ed26317e",
            "username": "foo",
            "consumer": { "id": "89a41fef-3b40-4bb0-b5af-33da57a7ffcf" }
        }
    ]
}
```

`username or id`: The username or id of the consumer whose credentials need to be listed

#### [Permalink](https://docs.konghq.com/hub/kong-inc/basic-auth/#retrieve-the-consumer-associated-with-a-credential)Retrieve the Consumer associated with a Credential <a href="#retrieve-the-consumer-associated-with-a-credential" id="retrieve-the-consumer-associated-with-a-credential"></a>

**Note:** This endpoint was introduced in Kong 0.11.2.

It is possible to retrieve a [Consumer](https://docs.konghq.com/latest/admin-api/#consumer-object) associated with a basic-auth Credential using the following request:

```
curl -X GET http://kong:8001/basic-auths/{username or id}/consumer

{
   "created_at":1507936639000,
   "username":"foo",
   "id":"c0d92ba9-8306-482a-b60d-0cfdd2f0e880"
}
```

`username or id`: The `id` or `username` property of the basic-auth Credential for which to get the associated [Consumer](https://docs.konghq.com/latest/admin-api/#consumer-object). Note that the `username` accepted here is **not** the `username` property of a Consumer.
