Improve middleware examples using auth (#668)

* Make `middleware::from_fn` examples less secure

* Also improve `extractor_middleware` example
This commit is contained in:
David Pedersen 2021-12-27 23:34:37 +01:00 committed by GitHub
parent 9d62b5c060
commit 1020d0144b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 7 deletions

View file

@ -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));

View file

@ -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
/// }