Setting cookies during server redirect #3486
-
I'm struggling with an OAuth flow that I'm trying to implement using Leptos (Axum). The basic steps I need to execute are: (user clicks the sign in button)
In general terms, what is the best way to do this? What I've tried so far applies a redirect, but it's not setting the cookie. A minimal version would look like: use leptos::prelude::*;
#[cfg(feature = "ssr")] use leptos_axum::{redirect, ResponseOptions};
#[cfg(feature = "ssr")] use http::{header, HeaderValue};
#[component]
pub fn SignIn() -> impl IntoView {
view! {
<button on:click=move |_| {
spawn_local(async move { handle_sign_in().await.unwrap() });
}>"Sign in"</button>
}
}
#[server]
async fn handle_sign_in() -> Result<(), ServerFnError> {
let Pkce {
verifier,
challenge,
} = generate_pkce();
let response = expect_context::<ResponseOptions>();
response.append_header(
header::SET_COOKIE,
HeaderValue::from_str(&format!("edgedb-pkce-verifier={verifier}"))?,
);
redirect(&format!("oauth/url/signin?challenge={challenge}"));
Ok(())
}
pub struct Pkce {
verifier: String,
challenge: String,
}
pub fn generate_pkce() -> Pkce {
Pkce {
verifier: "simplified example".to_string(),
challenge: "simplified example".to_string()
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Sorry for the slow response. I tried to create a small reproduction, but I found that it did set the cookie for me. But only temporarily, which was odd -- i.e., if I refresh the cookie is no longer there. Then I realized that it was because the cookie was scoped to the path In my repro, I was able to solve this by adding an appropriate response.append_header(
header::SET_COOKIE,
HeaderValue::from_str(&format!("edgedb-pkce-verifier=foo; Path=/"))?,
); YMMV — I am far from an expert at cookies. |
Beta Was this translation helpful? Give feedback.
-
Thanks, Greg! You're correct, the response.append_header(
header::SET_COOKIE,
HeaderValue::from_str(&format!(
"edgedb-pkce-verifier={verifier}; HttpOnly; Path=/; SameSite=Strict; Secure;"
))?,
); Please don't apologize for taking your time with replies. At the moment, there are only a few people that understand Leptos well. As things stabilize, the community will naturally have more depth on the bench, but in the meantime we need to take care of you and Ben. We all know 0.7 was a big lift. |
Beta Was this translation helpful? Give feedback.
Sorry for the slow response.
I tried to create a small reproduction, but I found that it did set the cookie for me. But only temporarily, which was odd -- i.e., if I refresh the cookie is no longer there.
Then I realized that it was because the cookie was scoped to the path
/api
, which meant I was seeing it in the response from the server function -- but not back on the home route/the route to which I was redirecting.In my repro, I was able to solve this by adding an appropriate
Path
to the cookie:YMMV — I am far from an expert at cookies.