Comments (2)
You need to use from_fn_with_state
when creating the middleware. Here is an example:
use axum::{
extract::FromRef,
http::Request,
middleware::{from_fn_with_state, Next},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
};
use axum_flash::{Flash, IncomingFlashes, Key};
#[tokio::main]
async fn main() {
let app_state = AppState {
flash_config: axum_flash::Config::new(Key::generate()),
};
// the endpoints that requires auth
let requires_auth = Router::new()
.route("/foo", get(|| async {}))
.layer(from_fn_with_state(app_state.clone(), auth_middleware));
let app = Router::new()
// `GET /` doesn't require because thats what our middleware
// redirects to
.route("/", get(root))
.merge(requires_auth)
.with_state(app_state);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
#[derive(Clone, FromRef)]
struct AppState {
flash_config: axum_flash::Config,
}
async fn root(flashes: IncomingFlashes) -> IncomingFlashes {
flashes
}
async fn auth_middleware<B>(flash: Flash, request: Request<B>, next: Next<B>) -> Response {
if authorized(&request) {
next.run(request).await.into_response()
} else {
(flash.error("Unauthorized"), Redirect::to("/")).into_response()
}
}
fn authorized<B>(request: &Request<B>) -> bool {
// TODO: actually check auth
false
}
from axum-flash.
Hey David,
wow, incredible! Thanks very much for the quick answer! It works perfectly.
Best regards
from axum-flash.
Related Issues (5)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from axum-flash.