Skip to content

Commit

Permalink
add HttpOnly and Secure
Browse files Browse the repository at this point in the history
  • Loading branch information
Logan Nielsen committed Nov 16, 2024
1 parent d154918 commit d414e8b
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions examples/oauth/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
//! CLIENT_ID=REPLACE_ME CLIENT_SECRET=REPLACE_ME cargo run -p example-oauth
//! ```

//! CLIENT_ID=1307445035985277011 CLIENT_SECRET=98ed2861cc2854044a25f7bdbd9a19f484d280f72210d07002d0c53604e275e5 cargo run -p example-oauth
//!
use anyhow::{anyhow, Context, Result};
use async_session::{MemoryStore, Session, SessionStore};
use axum::{
Expand All @@ -28,6 +30,7 @@ use std::env;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

static COOKIE_NAME: &str = "SESSION";
static CSRF_TOKEN: &str = "csrf_token";

#[tokio::main]
async fn main() {
Expand Down Expand Up @@ -153,7 +156,7 @@ async fn discord_auth(
// Create session to store csrf_token
let mut session = Session::new();
session
.insert("csrf_token", &csrf_token)
.insert(CSRF_TOKEN, &csrf_token)
.context("failed in inserting CSRF token into session")?;

// Store the session in MemoryStore and retrieve the session cookie
Expand All @@ -164,7 +167,7 @@ async fn discord_auth(
.context("unexpected error retrieving CSRF cookie value")?;

// Attach the session cookie to the response header
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; Path=/");
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; HttpOnly; Secure; Path=/");
let mut headers = HeaderMap::new();
headers.insert(
SET_COOKIE,
Expand Down Expand Up @@ -235,7 +238,7 @@ async fn csrf_token_validation_workflow(

// Extract the CSRF token from the session
let stored_csrf_token = session
.get::<CsrfToken>("csrf_token")
.get::<CsrfToken>(CSRF_TOKEN)
.context("CSRF token not found in session")?
.to_owned();

Expand Down Expand Up @@ -295,7 +298,7 @@ async fn login_authorized(
.context("unexpected error retrieving cookie value")?;

// Build the cookie
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; Path=/");
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; HttpOnly; Secure; Path=/");

// Set cookie
let mut headers = HeaderMap::new();
Expand Down

0 comments on commit d414e8b

Please sign in to comment.