Rust WASM restful JWT auth API boilerplate: Rocket.rs + WASM + diesel.rs + Postgresql
An example how to set up Rust server restful API with JWT authentication and ORM under the hood.
- User passwords hashed (argon2)
Requirements
- Configure Rust to satisfy rocket.rs dependencies (Rust nightly build needed)
- Install Diesel ORM CLI and dependencies
cargo install diesel_cli
- Install and create Postgresql database. More info here
- Configure project environment variable in
.env
file taking username and passwork from Posgresql stepDATABASE_URL=postgres://username:password@localhost/database_name
Installation
-
First run the migration to create tables and schema
diesel migration run
-
Compile wasm front end
cd www wasm-pack build --target web cd ..
-
Compile the code and run
cargo run
-
Open WASM front-end at
localhost:8001
http://localhost:8001
If everything was installed right and compiles without errors you should see Rocekt server listening atAPI rout JWT protection
Routs can be protected through JWT check in the message Header
#[get("/sensitive")]
fn sensitive(key: ApiKey) -> String {
format!("Hello, you have been identified as {}", key.0)
}
API
JWT token life is set to 2 weeks. Can be changed
/user/register
curl -X POST \
http://localhost:8001/user/register \
-H 'content-type: application/json' \
-d '{ "email": "[email protected]",
"password": "12345"
}'
/auth/login
Get a jwt token for the user
curl -X POST \
http://localhost:8001/auth/login \
-H 'content-type: application/json' \
-d '{ "email": "[email protected]",
"password": "12345"
}'
/user
Call a protected route with a JWT in the HEADER authentication
(use the token returned from the /auth/login API)
curl -X GET \
http://localhost:8001/user/sensitive \
-H 'authentication: eyJ0eXAiOiJKV1QiLCJraWQiOm51bGwsImFsZyI6IkhTMjU2In0.eyJpc3MiOm51bGwsInN1YiI6InRlc3QiLCJhdWQiOm51bGwsImV4cCI6MTU3MzAyNzg5MSwibmJmIjpudWxsLCJpYXQiOm51bGwsImp0aSI6bnVsbH0.DJ5tb/ic91oULyMjZMeam9kMU31sxGSxSnTmTppUhdA'