An example how to set up Rust server restful API with JWT authentication and ORM under the hood.
- User passwords hashed (argon2)
- 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
-
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
If everything was installed right and compiles without errors you should see Rocekt server listening at http://localhost:8001
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)
}
curl -X POST \
http://localhost:8001/user/register \
-H 'content-type: application/json' \
-d '{ "email": "some@email.com",
"password": "12345"
}'
Get a jwt token for the user
curl -X POST \
http://localhost:8001/auth/login \
-H 'content-type: application/json' \
-d '{ "email": "some@email.com",
"password": "12345"
}'
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'