rocket-firebase-auth

status crate codecov

Firebase Auth with Rocket, batteries included

Getting started

1. Set Firebase service account keys as env variables

If you haven't already, create a service account in Firebase for the Rocket backend you are creating. Generate a new private key and copy-paste the generated json into a firebase-credentials.json file.

json { "type": "*********", "project_id": "***********", "private_key_id": "*************", "private_key": "*****************", "client_email": "*********", "client_id": "*******", "auth_uri": "********", "token_uri": "********", "auth_provider_x509_cert_url": "********", "client_x509_cert_url": "********" }

Don't forget to add the firebase-credentials.json file to your .gitignore.

```gitignore

Firebase service account's secret credentials

firebase-credentials.json ```

2. Create a FirebaseAuth instance and add to server state

Add rocket-firebase-auth to your project.

toml rocket_firebase_auth = "0.2.0"

Now, you can create a FirebaseAuth struct by reading the json file with a helper function included with the default import.

```rust use rocket::{Build, Rocket}; use rocketfirebaseauth::FirebaseAuth;

pub struct ServerState { pub auth: FirebaseAuth }

[rocket::launch]

async fn rocket() -> Rocket { let firebaseauth = FirebaseAuth::tryfromjsonfile("firebase-credentials.json") .expect("Failed to read Firebase credentials");

rocket::build()
    .mount("/", routes![hello_world])
    .manage(ServerState {
        auth: firebase_auth
    })

} ```

3. Verify the token from the endpoint function

On endpoints that we except to receive Authorization headers containing our encoded Firebase tokens from the client, we can add a field to the endpoint function. Running the Jwt::verify() function will decode the token, where you can get the Firebase uid.

```rust

[get("/")]

async fn helloworld( state: &State, token: BearerToken, ) -> status::Accepted { let uid = Jwt::verify(&token.0, &state.auth) .mapok(|decodedtoken| decodedtoken.uid) .await .unwrap();

status::Accepted(Some(format!("uid: {uid}")))

} ```

Example project

For a more detailed example with a frontend example as well, checkout the example projects .

Contribute

Any contributions (PRs, Issues) are welcomed!

License

MIT