本示例代码来源于本人开源项目batata(https://github.com/easynet-cn/batata),致力于实现兼容nacos服务治理平台。
实例代码实现了兼容nacos的JWT Token编码和解码。
主要用到了以下项目:
1:actix-web:https://github.com/actix/actix-web
2:jsonwebtoken:https://github.com/Keats/jsonwebtoken
Nacos JWT Token Payload
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NacosJwtPayload {
pub sub: String,
pub exp: i64,
}
编解码
需要注意Naocs JWT Header中不会写入type
use crate::common::model::{NacosJwtPayload, NacosUser};
use chrono;
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
pub fn decode_jwt_token(
token: &str,
secret_key: &str,
) -> jsonwebtoken::errors::Result<jsonwebtoken::TokenData<crate::service::auth::NacosJwtPayload>> {
decode::<crate::service::auth::NacosJwtPayload>(
token,
&DecodingKey::from_base64_secret(secret_key).unwrap(),
&Validation::default(),
)
}
pub fn encode_jwt_token(
user: &NacosUser,
secret_key: &str,
token_expire_seconds: i64,
) -> jsonwebtoken::errors::Result<String> {
let exp = chrono::Utc::now()
.checked_add_signed(chrono::Duration::seconds(token_expire_seconds))
.expect("valid timestamp")
.timestamp();
let payload = NacosJwtPayload {
sub: user.username.clone(),
exp,
};
let header = Header {
typ: None,
alg: Algorithm::HS256,
cty: None,
jku: None,
jwk: None,
kid: None,
x5u: None,
x5c: None,
x5t: None,
x5t_s256: None,
};
encode(
&header,
&payload,
&EncodingKey::from_base64_secret(secret_key).unwrap(),
)
}