同步操作将从 mirrors_maxcountryman/axum-login 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
🪪 Session-based user authentication for Axum.
axum-login
is a Tower middleware providing session-based user authentication for axum
applications.
axum-sessions
to provide flexible sessionstower_http::auth::RequireAuthorizationLayer
to protect routesNote
axum-login
implements a fundamental pattern for user authentication, however some features may be missing. Folks are encouraged to make suggestions for extensions to the library.
To use the crate in your project, add the following to your Cargo.toml
file:
[dependencies]
axum-login = "0.4.1"
axum
applications can use the middleware via the auth layer.
axum
Exampleuse axum::{response::IntoResponse, routing::get, Extension, Router};
use axum_login::{
axum_sessions::{async_session::MemoryStore, SessionLayer},
secrecy::SecretVec,
AuthLayer, AuthUser, RequireAuthorizationLayer, SqliteStore,
};
use rand::Rng;
use sqlx::sqlite::SqlitePoolOptions;
#[derive(Debug, Default, Clone, sqlx::FromRow)]
struct User {
id: i64,
password_hash: String,
name: String,
}
impl AuthUser for User {
fn get_id(&self) -> String {
format!("{}", self.id)
}
fn get_password_hash(&self) -> SecretVec<u8> {
SecretVec::new(self.password_hash.clone().into())
}
}
type AuthContext = axum_login::extractors::AuthContext<User, SqliteStore<User>>;
#[tokio::main]
async fn main() {
let secret = rand::thread_rng().gen::<[u8; 64]>();
let session_store = MemoryStore::new();
let session_layer = SessionLayer::new(session_store, &secret).with_secure(false);
let pool = SqlitePoolOptions::new()
.connect("sqlite/user_store.db")
.await
.unwrap();
let user_store = SqliteStore::<User>::new(pool);
let auth_layer = AuthLayer::new(user_store, &secret);
async fn login_handler(mut auth: AuthContext) {
let pool = SqlitePoolOptions::new()
.connect("sqlite/user_store.db")
.await
.unwrap();
let mut conn = pool.acquire().await.unwrap();
let user: User = sqlx::query_as("select * from users where id = 1")
.fetch_one(&mut conn)
.await
.unwrap();
auth.login(&user).await.unwrap();
}
async fn logout_handler(mut auth: AuthContext) {
dbg!("Logging out user: {}", &auth.current_user);
auth.logout().await;
}
async fn protected_handler(Extension(user): Extension<User>) -> impl IntoResponse {
format!("Logged in as: {}", user.name)
}
let app = Router::new()
.route("/protected", get(protected_handler))
.route_layer(RequireAuthorizationLayer::<User>::login())
.route("/login", get(login_handler))
.route("/logout", get(logout_handler))
.layer(auth_layer)
.layer(session_layer);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
You can find this example as well as other example projects in the example directory.
See the crate documentation for more usage information.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。