Bearer authentication in Ktor Server
The Bearer authentication scheme is a part of the HTTP framework used for access control and authentication. This scheme involves security tokens called bearer tokens. The Bearer authentication scheme is used as part of OAuth or JWT, but you can also provide custom logic for authorizing bearer tokens.
You can get general information about authentication in Ktor in the Authentication and authorization in Ktor Server section.
Add dependencies
To enable bearer authentication, you need to include the ktor-server-auth artifact in the build script:
Bearer authentication flow
In general, the Bearer authentication flow might look as follows:
- After a user successfully authenticates and authorizes access, the server returns an access token to the client. 
- The client can make a request to a protected resource with a token passed in the - Authorizationheader using the- Bearerschema.GET http://localhost:8080/ Authorization: Bearer abc123
- A server receives a request and validates a token. 
- After validation, a server responds with the contents of a protected resource. 
Install bearer authentication
To install the bearer authentication provider, call the bearer function inside the install block:
You can optionally specify a provider name that can be used to authenticate a specified route.
Configure bearer authentication
To get a general idea of how to configure different authentication providers in Ktor, see Configure Authentication. In this section, we'll see on configuration specifics of the bearer authentication provider.
Step 1: Configure a bearer provider
The bearer authentication provider exposes its settings via the BearerAuthenticationProvider.Configuration class. In the example below, the following settings are specified:
- The - realmproperty sets the realm to be passed in the- WWW-Authenticateheader.
- The - authenticatefunction checks the token sent by the client and returns a- UserIdPrincipalin the case of successful authentication or- nullif authentication fails.
Step 2: Protect specific resources
After configuring the bearer provider, you can protect specific resources in our application using the authenticate function. In the case of successful authentication, you can retrieve an authenticated UserIdPrincipal inside a route handler using the call.principal function and get a name of an authenticated user.