Skip to main content

encode

Function encode 

Source
pub fn encode(ctx: &Ctx, claims: &Claims) -> Result<String>
Expand description

Signs claims with the HS256 key derived from the SECRET_KEY_BASE Worker secret.

Same token as encode_with with Key::from_secret_key_base. The secret is read on every call; no D1 or KV operation.

§Errors

Error::Internal (500) when SECRET_KEY_BASE is not set or is shorter than 64 characters; the message names the fix (ocre secret, .dev.vars for ocre dev, ocre deploy uploads it).

§Examples

use axum::{Json, extract::State};
use ocre::{Ctx, Result, jwt::{self, Claims}};

// POST /api/auth/token, after checking the password:
async fn token(State(ctx): State<Ctx>) -> Result<Json<serde_json::Value>> {
    let user_id = 42;
    let token = jwt::encode(&ctx, &Claims::new(user_id.to_string(), 3600))?;
    Ok(Json(serde_json::json!({ "token": token, "expires_in": 3600 })))
}