Rust, Software Development

Actix-Web Basic And Bearer Authentication Examples

This post has code examples for Actix-Web Basic and Bearer authentications in Rust. In a Basic authentication scheme, a client transmits credentials as user Id and password pairs in base64 format. Meanwhile, a client sends a string token in a Bearer authentication. In either case, the server application must validate the credentials or token.

No JWT And Database for Authentication Examples

To keep things simple, the code examples for Actix-Web Basic and Bearer authentications do not use JWT and database. Therefore, we will compare the credentials or token against hard-coded string values.

Dependencies For Actix-Web Authentication Examples

For both authentication examples, we use the same Cargo.toml file with three dependencies.

Basic Authentication Example

For the Actix-web Basic Authentication example, we need the following imports.

Our main function is as follows. An Actix-Web App instance wraps up an instance of HttpAuthentication<BasicAuth, fn(...)>  to intercept requests to any defined routes.

All requests to /{id}/{name}/index.html go to the index function.

We need to define an asynchronous function. It receives HTTP requests along with the user credentials.

Then, we need another function to validate user credentials against hard-coded string values.

To test the codes, start up the application. Then, go to a URL, as shown in the video below. The user name and password are karl and password, respectively.

Bearer Authentication Example

The Actix-Web Bearer authentication example is slightly different from the previous codes. It needs to use Bearer-related imports.

The main function now uses HttpAuthentication::bearer instead of HttpAuthentication::basic.

The validator function now also accepts BearerAuth.

Lastly, we validate the token against a hard-coded value, which could be anything in real-life applications.

Testing these codes differs from the previous ones because we need a way to set the Authorization HTTP header before sending the request. For this example, we use Authorization: Bearer a-secure-token.

In Actix-Web, we perform authentication either via Basic or Bearer authentication. Each is unique in terms of coding and specific implementation.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like