Repository navigation
How to store the JWT token #1560
|
This may be more of a web newbie question than a loco question. How should I store the JWT token returned from the What resources would you recommend to learn about this? |
Replies: 2 comments
|
Hi @kevinclancy my favorite way is to store them in a secure http only cookie. You can do it by changing the config auth:
# JWT authentication
jwt:
# Secret key for token generation and verification
secret: vqc6o8vyjB2BtxUT3TOM
# Token expiration time in seconds
expiration: 604800 # 7 days
location:
from: Cookie
name: jwtthe name is the name of the cookie where the jwt will be stored. And this is the way i setup the cookie: #[debug_handler]
async fn login_admin(
State(ctx): State<AppContext>,
jar: CookieJar,
Json(params): Json<LoginParams>,
) -> Result<(CookieJar, Response)> {
let user = users::Model::find_by_email(&ctx.db, ¶ms.email).await?;
let valid = user.verify_password(¶ms.password);
if !valid {
return unauthorized("unauthorized!");
}
let roles = crate::models::_entities::roles::Model::find_by_user(&ctx.db, user.id).await?;
let admin_role = roles.iter().find(|r| r.name == "admin");
match admin_role {
Some(_) => {
let jwt_secret = ctx.config.get_jwt_config()?;
let token = user
.generate_jwt(&jwt_secret.secret, jwt_secret.expiration)
.or_else(|_| unauthorized("unauthorized!"))?;
dbg!(&token);
let cookie = Cookie::build(("jwt", token.clone()))
.secure(true)
.http_only(true);
Ok((
jar.add(cookie),
format::json(LoginResponse::new(&user, &token))?,
))
}
None => {
return unauthorized("unauthorized!");
}
}
} |
|
Instead of in a cookie, another option is to use sessionStorage or localStorage. There are pros and cons to each option and opinions over which one to use vary. See here for some clarification. Generally cookies are easiest if you use server side rendering. If you have a single page app where rendering is done in javascript session- or localStorage might be preferable. |
Hi @kevinclancy my favorite way is to store them in a secure http only cookie.
You can do it by changing the config
For example in config/development.yaml
the name is the name of the cookie where the jwt will be stored.
And this is the way i setup the cookie: