LGUG2Z / rocket_oauth2

OAuth2 for Rocket applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

rocket_oauth2

maintenance: passive

rocket_oauth2 helps set up OAuth 2.0 sign-in or authorization in Rocket applications.

Major Versions

  • 0.4.x, compatible with rocket 0.4.x, are based on the master branch
  • 0.5.0-rc.x, compatible with rocket 0.5.0-rc.x, are based on the next branch

Quickstart Example

For more detailed examples and explanations, see the crate documentation and the projects in the repository's examples directory.

Code

use rocket::http::{Cookie, Cookies, SameSite};
use rocket::Request;
use rocket::response::Redirect;
use rocket_oauth2::{OAuth2, TokenResponse};

struct GitHub;

#[get("/login/github")]
fn github_login(oauth2: OAuth2<GitHub>, mut cookies: Cookies<'_>) -> Redirect {
    oauth2.get_redirect(&mut cookies, &["user:read"]).unwrap()
}

#[get("/auth/github")]
fn github_callback(token: TokenResponse<GitHub>, mut cookies: Cookies<'_>) -> Redirect
{
    cookies.add_private(
        Cookie::build("token", token.access_token().to_string())
            .same_site(SameSite::Lax)
            .finish()
    );
    Redirect::to("/")
}

fn main() {
    rocket::ignite()
        .mount("/", routes![github_callback, github_login])
        .attach(OAuth2::<GitHub>::fairing("github"))
        .launch();
}

Configuration (Rocket.toml)

[global.oauth.github]
provider = "GitHub"
client_id = "..."
client_secret = "..."
redirect_uri = "http://localhost:8000/auth/github"

License

rocket_oauth2 is licensed under either of the following, at your option:

About

OAuth2 for Rocket applications

License:Apache License 2.0


Languages

Language:Rust 100.0%