After migrating from a Node.js Express server to Rust Actix Web, our frontend login redirect act changed unexpectedly, even though the client code wasn’t updated.
// Check authentication status in a Node.js service
export const verifyAuth = asyncHandler(async (req, res) => {
const authCookie = req.cookies.authCookie;
if (!authCookie) return res.status(401).json({ message: "Login required!" });
try {
const userPayload = jwt.verify(authCookie, process.env.SECRET_KEY);
res.status(200).json(true);
} catch (error) {
res.status(401).json(false);
}
});
// Validate user session in a Rust service
pub async fn auth_check(req: HttpRequest) -> impl Responder {
match jwt_tools::validate_token(&req) {
Ok(_) => HttpResponse::Ok().json(true),
Err(_) => HttpResponse::Unauthorized().json(false),
}
}
pub fn validate_token(req: &HttpRequest) -> Result<UserClaims, String> {
if let Some(auth) = req.headers().get("Authorization") {
if let Ok(token_str) = auth.to_str() {
let parts: Vec<&str> = token_str.splitn(2, ' ').collect();
if parts.len() == 2 && parts[0] == "Bearer" {
return decode_jwt(parts[1]);
}
}
}
Err("Missing or invalid token.".to_string())
}
fn decode_jwt(token: &str) -> Result<UserClaims, String> {
// Custom token decoding implementation
Ok(UserClaims { id: 0, email: "example@example.com".to_string(), exp: 0 })
}
#[derive(Serialize, Deserialize)]
pub struct UserClaims {
pub id: i32,
pub email: String,
pub exp: usize,
}