I’m attempting to implement an authentication middleware, but an Axum error occurs whenever I set a state:
275 | pub fn layer<L>(self, layer: L) -> Router<S>
| ----- required by a bound in this associated function
...
278 | L::Service: Service<Request> + Clone + Send + 'static,
| ^^^^^^^^^^^^^^^^ required by this bound in `Router::<S>::layer`
My code:
pub async fn auth(
State(state): State<Arc<Mutex<AppState>>>,
headers: HeaderMap,
request: Request,
next: Next,
) -> Result<impl IntoResponse, StatusCode> {
let config = config::Config::init();
let auth_secret = &config.get_auth_token_secret();
match is_valid_token(headers, auth_secret) {
Some(user) => {
info!("Auth middleware - API user ID authorize: {:?}", user);
_ = state.lock().await;
let response = next.run(request).await;
Ok(response)
}
None => Err(StatusCode::UNAUTHORIZED),
}
}
pub fn is_valid_token(headers: HeaderMap, auth_secret: &str) -> Option<String> {
match headers.get("Authorization") {
Some(token) => {
let value = token.to_str().unwrap_or("");
let token = value.replace("Bearer ", "");
let validation = Validation::new(Algorithm::HS256);
match decode::<JWTClaims>(
&token,
&DecodingKey::from_secret(auth_secret.as_ref()),
&validation,
) {
Ok(claims) => Some(claims.claims.sub.clone()),
Err(_) => None,
}
}
None => None,
}
}
I’m tried following axum::middleware::from_fn_with_state docs rules, but it’s not working yet.
New contributor
mike is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.