Getting Started with Bearer Token Authentication
Bearer Token authentication is one of the most popular forms of authentication and is widely used due to its perceived security. This guide will walk you through how to implement bearer token authentication in Glee.
Below is a sample asyncapi.yaml
for a server with security requirements and a user password security scheme:
1## Server AsyncAPI Schema
2asyncapi: 3.0.0
3info:
4 title: AsyncAPI IMDB Server
5 version: 1.0.0
6 description: This app is a dummy server that streams trending/upcoming anime.
7servers:
8 trendingAnimeServer:
9 host: 'localhost:8081'
10 protocol: http
11 security:
12 - $ref: '#/components/securitySchemes/token'
13
14 ...
15
16components:
17 securitySchemes:
18 token:
19 type: http
20 scheme: bearer
21 bearerFormat: JWT
22
A sample asyncapi.yaml
for a client that implements some of the requirements of the server above:
1## Client AsyncAPI Schema
2servers:
3 trendingAnime:
4 host: localhost:8081
5 protocol: http
6 security:
7 - $ref: '#/components/securitySchemes/token'
8 testwebhook:
9 host: localhost:9000
10 protocol: ws
11x-remoteServers:
12 - trendingAnime
13
14 ...
15
16components:
17 securitySchemes:
18 token:
19 type: http
20 scheme: bearer
21 bearerFormat: JWT
22
The Client asyncapi.yaml
file doesn't need to implement all the security requirements of the server; it only needs to implement the ones it uses, like http (bearer token) here.
Client Side
Following the client asyncapi.yaml
file above, create a file named trendingAnime.ts
in the auth
directory, since that is the server that has the security property.
touch auth/trendingAnime.ts
When using the bearer
security scheme, pass the parameters as follows:
1export async function clientAuth({ parsedAsyncAPI, serverName }) {
2 return {
3 token: process.env.TOKEN
4 }
5}
Glee will utilize the token
for server authentication, employing it in the header with the format: Authorization: Bearer \{token\}
.
Server Side
From the server asyncapi.yaml
file above, create a file named trendingAnimeServer.ts
in the auth
directory, since that is the server that has the security property.
touch auth/trendingAnimeServer.ts
On the server side, you can retrieve the values as follows:
1
2export async function serverAuth({ authProps, done }) {
3 authProps.getToken()
4 // Your authentication logic here...
5 done(true || false)
6}
7
So, getToken()
returns a string containing the token sent from the client.