mirror of
https://github.com/tokio-rs/axum.git
synced 2025-10-02 15:24:54 +00:00
Improve middleware examples using auth (#668)
* Make `middleware::from_fn` examples less secure * Also improve `extractor_middleware` example
This commit is contained in:
parent
9d62b5c060
commit
1020d0144b
@ -43,16 +43,23 @@ use tower_service::Service;
|
|||||||
/// use axum_extra::middleware::{self, Next};
|
/// use axum_extra::middleware::{self, Next};
|
||||||
///
|
///
|
||||||
/// async fn auth<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
|
/// async fn auth<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
|
||||||
/// let auth_header = req.headers().get(http::header::AUTHORIZATION);
|
/// let auth_header = req.headers()
|
||||||
|
/// .get(http::header::AUTHORIZATION)
|
||||||
|
/// .and_then(|header| header.to_str().ok());
|
||||||
///
|
///
|
||||||
/// match auth_header {
|
/// match auth_header {
|
||||||
/// Some(auth_header) if auth_header == "secret" => {
|
/// Some(auth_header) if token_is_valid(auth_header) => {
|
||||||
/// Ok(next.run(req).await)
|
/// Ok(next.run(req).await)
|
||||||
/// }
|
/// }
|
||||||
/// _ => Err(StatusCode::UNAUTHORIZED),
|
/// _ => Err(StatusCode::UNAUTHORIZED),
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
|
/// fn token_is_valid(token: &str) -> bool {
|
||||||
|
/// // ...
|
||||||
|
/// # false
|
||||||
|
/// }
|
||||||
|
///
|
||||||
/// let app = Router::new()
|
/// let app = Router::new()
|
||||||
/// .route("/", get(|| async { /* ... */ }))
|
/// .route("/", get(|| async { /* ... */ }))
|
||||||
/// .route_layer(middleware::from_fn(auth));
|
/// .route_layer(middleware::from_fn(auth));
|
||||||
|
@ -62,16 +62,20 @@ use tower_service::Service;
|
|||||||
/// .and_then(|headers| headers.get(http::header::AUTHORIZATION))
|
/// .and_then(|headers| headers.get(http::header::AUTHORIZATION))
|
||||||
/// .and_then(|value| value.to_str().ok());
|
/// .and_then(|value| value.to_str().ok());
|
||||||
///
|
///
|
||||||
/// if let Some(value) = auth_header {
|
/// match auth_header {
|
||||||
/// if value == "secret" {
|
/// Some(auth_header) if token_is_valid(auth_header) => {
|
||||||
/// return Ok(Self);
|
/// Ok(Self)
|
||||||
/// }
|
/// }
|
||||||
|
/// _ => Err(StatusCode::UNAUTHORIZED),
|
||||||
/// }
|
/// }
|
||||||
///
|
|
||||||
/// Err(StatusCode::UNAUTHORIZED)
|
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
|
/// fn token_is_valid(token: &str) -> bool {
|
||||||
|
/// // ...
|
||||||
|
/// # false
|
||||||
|
/// }
|
||||||
|
///
|
||||||
/// async fn handler() {
|
/// async fn handler() {
|
||||||
/// // If we get here the request has been authorized
|
/// // If we get here the request has been authorized
|
||||||
/// }
|
/// }
|
||||||
|
Loading…
x
Reference in New Issue
Block a user