Authentication
Probably the quickest way to add authentication to an application is with Barricade. Barricade handles login and registration pages and connects to your Postgres database.
Installing Barricade
We've already created the tables that Barricade needs in the migrations section. so we just need to add configuration .devcontainer/docker-compose.yml
.
auth:
image: purtontech/barricade:1.2.0
env_file:
- .env
depends_on:
db:
condition: service_healthy
We also need to add a health check to our db section so that we know when the database is ready.
db:
...
healthcheck:
test:
interval: 10s
timeout: 5s
retries: 5
Add the following to you .devcontainer/.env
# Barricade config
SECRET_KEY=190a5bf4b3cbb6c0991967ab1c48ab30790af876720f1835cbbf3820f4f5d949
ENABLE_EMAIL_OTP='true'
FORWARD_URL=app
FORWARD_PORT=3000
# Any requests that meet the following regular expressions
# with pass through. i.e. They don't require auth.
SKIP_AUTH_FOR=/static*
REDIRECT_URL='/'
# Send all email to mailhog
SMTP_HOST=smtp
SMTP_PORT=1025
SMTP_USERNAME=thisisnotused
SMTP_PASSWORD=thisisnotused
SMTP_TLS_OFF='true'
RESET_DOMAIN=http://localhost:7100
RESET_FROM_EMAIL_ADDRESS=[email protected]
Testing Barricade
After rebuilding your devcontainer you will need to register as a user. Make sure you server is running again i.e.
Expose port 9090 from your devcontainer then go to http://localhost:9090
and sign up.
Accessing the user from Axum
We need to create a file called crates/axum-server/src/authentification.rs
and add the following code.
// Extract the barricade
use ;
use Parts;
// From a request extract our authentication token.
Connect this into our crates/axum-server/src/main.rs
by adding a line mod authentication
at the top of the main.rs
.
Using the Authentication Extractor
Form within a handler you can access the user id like so...
pub async
The user_id
is the database ID of the user in the users
table.