Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 214 additions & 0 deletions authentication/basic-authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
---
lastmod: 2026-11-30
date: 2020-05-25
linktitle: Basic Authentication
title: Basic Authentication
description: Protect KrakenD endpoints with HTTP Basic Authentication, checking usernames and bcrypt passwords from an htpasswd file or the configuration.
weight: 10
menu:
community_current:
parent: "080 Authentication & Authorization"
meta:
source: https://github.com/krakend/krakend-basicauth
namespace:
- auth/basic
log_prefix:
- "[SERVICE: auth/basic]"
- "[ENDPOINT: GET /foo][auth/basic]"
scope:
- service
- endpoint
---
The **Basic Authentication** component protects selected endpoints with usernames and passwords sent in the `Authorization` header, as defined in [RFC 7617](https://www.rfc-editor.org/rfc/rfc7617.html). KrakenD checks the credentials at the router level, so the backend never receives a request that fails the authentication. Use it for internal tools, legacy clients, or service accounts where tokens are not an option. For end users, [JWT validation](/docs/authorization/jwt-validation/) is a safer choice.

{{< note title="No longer a plugin" type="info" >}}
KrakenD Enterprise v2.2 deprecated the `basic-auth` plugin in favor of the native `auth/basic` component, and v3.0 removed it. If your configuration still uses the plugin, follow the steps to [upgrade from plugin-based Basic Auth](/docs/authentication/basic-authentication/#upgrade-from-plugin-based-basic-auth).
{{< /note >}}

## How Basic Authentication Works
KrakenD reads the users from a regular `.htpasswd` file, from the `users` of the configuration, or from both. Passwords must be `bcrypt` hashes. The `htpasswd` command is the only tool you need to create them (it is part of the `apache2-utils` package in Linux).

When KrakenD starts, it loads the `.htpasswd` file in memory, so checking the credentials doesn't read from disk. If KrakenD can't read the file, it doesn't start.

Only the endpoints with an `auth/basic` entry require credentials. The rest stay public or use other authentication methods. When a request has no valid credentials, KrakenD returns a `401 Unauthorized` status code with no body.

## Basic Authentication Configuration
You can place the `auth/basic` namespace at the **service level**, at the **endpoint level**, or at **both**. The service level declares the users that any protected endpoint shares, and each endpoint enables the authentication with its own `auth/basic` entry:

- An endpoint with an empty `"auth/basic": {}` uses the users of the service level.
- An endpoint that declares its own users, with `htpasswd_path` or `users`, uses only those and ignores the users of the service level.
- The entries of `users` overwrite the users with the same name in the `.htpasswd` file.

For instance, the following configuration protects `/user/{id}` with the users of the service level, and `/checkout` with the users of a different file:

```json
{
"version": 4,
"extra_config": {
"auth/basic": {
"@comment": "Users for any endpoint with an empty auth/basic entry, plus the ones in the htpasswd file",
"htpasswd_path": "/path/to/.htpasswd",
"users": {
"admin": "$2y$05$HpdPmv2Z3h3skMCVaf/CEep/UUBuhZ...",
"user2": "$2y$05$HpdPmv2Z3h3skMCVaf/CEep/UUBuhZ..."
}
}
},
"endpoints": [
{
"endpoint": "/user/{id}",
"extra_config": {
"@comment": "The empty entry enables basic auth with the service users",
"auth/basic": {}
},
"backend": [
{
"host": ["http://localhost:8080"],
"url_pattern": "/__debug/user/{id}"
}
]
},
{
"endpoint": "/checkout",
"extra_config": {
"@comment": "This endpoint uses only the users of its own file",
"auth/basic": {
"htpasswd_path": "/path/to/.htpasswd_secondary"
}
},
"backend": [
{
"host": ["http://localhost:8080"],
"url_pattern": "/__debug/checkout"
}
]
}
]
}
```

{{< schema data="auth/basic.json" >}}

## Browser Login Prompt with the Realm
By default, the `401` responses don't carry a `WWW-Authenticate` header. When you set a `realm`, every `401` of the protected endpoints carries `WWW-Authenticate: Basic realm="<your realm>"`, the challenge that RFC 7617 describes, and browsers show their native login prompt when they receive it.

{{< note title="The realm makes browser applications show a login prompt" type="warning" >}}
Browsers show the login prompt for any `401` with this header, including the requests that a browser application sends with `fetch` or `XMLHttpRequest`. If a browser application consumes your API and handles the authentication itself, don't set a `realm`.
{{< /note >}}

The `realm` works at the service and the endpoint levels. An endpoint without its own `realm` uses the one of the service level. For example, this endpoint asks for credentials with the realm `Restricted area`:

```json
{
"version": 4,
"endpoints": [
{
"endpoint": "/admin",
"extra_config": {
"auth/basic": {
"realm": "Restricted area",
"htpasswd_path": "/path/to/.htpasswd"
}
},
"backend": [
{
"host": ["http://localhost:8080"],
"url_pattern": "/__debug/admin"
}
]
}
]
}
```

A request without credentials gets the challenge:

{{< terminal title="Request without credentials" >}}
curl -i http://localhost:8080/admin
HTTP/1.1 401 Unauthorized
Www-Authenticate: Basic realm="Restricted area"
Content-Length: 0
{{< /terminal >}}

## Invalid Users in the Configuration
Every value of `users` must be a string with a `bcrypt` hash. When a value is not a string, KrakenD logs an error and ignores that user, who can't authenticate:

```log
ERROR: [ENDPOINT: GET /foo][auth/basic] The password hash of user admin is not a string, ignoring the user
```

If ignoring the invalid users leaves an endpoint with no users at all, the endpoint rejects every request instead of using the users of the service level.

## User Administration
KrakenD loads the `.htpasswd` file and the `users` only during startup. To change who can access the endpoints, restart or redeploy KrakenD.

KrakenD only accepts passwords hashed with `bcrypt`. Generate a file with the following command (notice the `-B` flag for bcrypt):

{{< terminal title="Generate access file" >}}
htpasswd -Bbc .htpasswd yourUser yourPassword
{{< /terminal >}}

Or print the result to stdout instead:

{{< terminal title="Ask for password and create hash" >}}
htpasswd -nB yourUser
New password:
Re-type new password:
yourUser:$2y$05$s8eiQOQtfvOPB3K4vr212eZyZFdtdnKap6RfEVd479xXtXlfx7Nsq
{{< /terminal >}}

Each line holds the user and the password hash, separated by a colon. Add it to the `.htpasswd` file, or move the hash to the `users` of the configuration. KrakenD accepts files with Unix or Windows (CRLF) line endings. To delete a user, remove its line from the file.

## Upgrade from Plugin-Based Basic Auth
KrakenD Enterprise v2.2 deprecated the basic authentication plugin, and v3.0 removed it. If your configuration still uses the plugin, switch to the configuration of the native component, which offers the following **benefits**:

- All rejections appear in the telemetry.
- You can override the configuration at the endpoint level.
- The configuration is easier to maintain.

The following diff shows the same setup with the removed plugin and with the native component:

```diff
{
"version": 4,
- "plugin": {
- "pattern": ".so",
- "folder": "/opt/krakend/plugins/"
- },
"extra_config": {
- "plugin/http-server": {
- "name": ["basic-auth"],
- "basic-auth": {
- "htpasswd_path": "/path/to/.htpasswd",
- "endpoints": ["/user/{id}", "/checkout"],
- "users": {
- "admin": "$2y$05$HpdPmv2Z3h3skMCVaf/CEep/UUBuhZ..."
- }
- }
- }
+ "auth/basic": {
+ "htpasswd_path": "/path/to/.htpasswd",
+ "users": {
+ "admin": "$2y$05$HpdPmv2Z3h3skMCVaf/CEep/UUBuhZ..."
+ }
+ }
},
"endpoints": [
{
"endpoint": "/user/{id}",
+ "extra_config": {
+ "auth/basic": {}
+ },
"backend": [{"host": ["http://localhost:8080"], "url_pattern": "/__debug/user/{id}"}]
}
]
}
```

To upgrade, follow these steps:

1. Remove the `plugin` entry.
2. Move the settings from `extra_config` / `plugin/http-server` / `basic-auth` to `extra_config` / `auth/basic`.
3. Remove the `endpoints` list of the settings.
4. Add an empty `auth/basic` entry to the `extra_config` of each protected endpoint.
5. Optionally, override the settings on a specific endpoint with its own values.
6 changes: 3 additions & 3 deletions authorization/_index.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
lastmod: 2024-11-20
lastmod: 2026-11-30
date: 2024-11-20
linktitle: Intro to AuthZ and AuthN
title: Authorization and Authentication (authZ + authN)
Expand Down Expand Up @@ -47,9 +47,9 @@ You can make many possible combinations, and the independence of these two sides
## Authentication (AuthN)
Authentication takes care of **recognizing** legitimate users. Generally, you will delegate the authentication to an Identity Provider (for short, **IdP**). The IdP can be your existing monolithic application that checks a user and password or a more fancy IdP using industry standards, whether it's SaaS or self-hosted (e.g., Auth0, Azure AD, Google Firebase, Keycloak...). The IdP takes care of the authentication methods you want to support. E.g., Password-based User Authentication, One-time Password (OTP), Single Sign-On (SSO), Biometric/Passwordless Authentication, etc. The IdP will then generate a signed token that KrakenD can use to authorize the user.

Aside from tokens, you can also use a certificate to authenticate to your gateway or the gateway to connect to a backend service. Both scenarios are supported on [Mutual TLS (mTLS)](/docs/authorization/mutual-authentication/).
Aside from tokens, you can also use a certificate to authenticate to your gateway or the gateway to connect to a backend service. Both scenarios are supported on [Mutual TLS (mTLS)](/docs/authorization/mutual-authentication/). For simpler setups, [Basic Authentication](/docs/authentication/basic-authentication/) checks a username and password against an htpasswd file.

In addition, the Enterprise Edition adds other methods like [Google Cloud service-to-service](/docs/enterprise/authentication/gcloud/) or more "classic" (and less secure) authentication methods, such as [API-key authentication](/docs/enterprise/authentication/api-keys/), [Basic Authentication](/docs/enterprise/authentication/basic-authentication/), or even [Microsoft's NTLM (NT Lan Manager) Authentication](/docs/enterprise/authentication/ntlm/).
In addition, the Enterprise Edition adds other methods like [Google Cloud service-to-service](/docs/enterprise/authentication/gcloud/) or more "classic" (and less secure) authentication methods, such as [API-key authentication](/docs/enterprise/authentication/api-keys/), or even [Microsoft's NTLM (NT Lan Manager) Authentication](/docs/enterprise/authentication/ntlm/).

## Authorization (AuthZ)
Authorization determines what authenticated users or systems are **permitted** to do. KrakenD provides flexible options for fine-grained access control. The most common method is Token-based authorization (see below). In addition to JWT, you can also use [OAuth2 Client Credentials](/docs/enterprise/authorization/client-credentials/) for machine-to-machine communication. KrakenD verifies the client's credentials with this flow and enforces scope-based access controls.
Expand Down
Loading