mirror of
https://github.com/tokio-rs/axum.git
synced 2024-11-23 07:39:25 +01: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
2 changed files with 18 additions and 7 deletions
|
@ -43,16 +43,23 @@ use tower_service::Service;
|
|||
/// use axum_extra::middleware::{self, Next};
|
||||
///
|
||||
/// 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 {
|
||||
/// Some(auth_header) if auth_header == "secret" => {
|
||||
/// Some(auth_header) if token_is_valid(auth_header) => {
|
||||
/// Ok(next.run(req).await)
|
||||
/// }
|
||||
/// _ => Err(StatusCode::UNAUTHORIZED),
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn token_is_valid(token: &str) -> bool {
|
||||
/// // ...
|
||||
/// # false
|
||||
/// }
|
||||
///
|
||||
/// let app = Router::new()
|
||||
/// .route("/", get(|| async { /* ... */ }))
|
||||
/// .route_layer(middleware::from_fn(auth));
|
||||
|
|
|
@ -62,16 +62,20 @@ use tower_service::Service;
|
|||
/// .and_then(|headers| headers.get(http::header::AUTHORIZATION))
|
||||
/// .and_then(|value| value.to_str().ok());
|
||||
///
|
||||
/// if let Some(value) = auth_header {
|
||||
/// if value == "secret" {
|
||||
/// return Ok(Self);
|
||||
/// match auth_header {
|
||||
/// Some(auth_header) if token_is_valid(auth_header) => {
|
||||
/// Ok(Self)
|
||||
/// }
|
||||
/// _ => Err(StatusCode::UNAUTHORIZED),
|
||||
/// }
|
||||
///
|
||||
/// Err(StatusCode::UNAUTHORIZED)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn token_is_valid(token: &str) -> bool {
|
||||
/// // ...
|
||||
/// # false
|
||||
/// }
|
||||
///
|
||||
/// async fn handler() {
|
||||
/// // If we get here the request has been authorized
|
||||
/// }
|
||||
|
|
Loading…
Reference in a new issue