#[pre_authorize]Expand description
Flexible method security annotation with SpEL-like expressions.
§Spring Security Equivalent
@PreAuthorize("...")
§Supported Expressions
| Actix Security | Spring Security |
|---|---|
#[pre_authorize(authenticated)] | @PreAuthorize("isAuthenticated()") |
#[pre_authorize(role = "ADMIN")] | @PreAuthorize("hasRole('ADMIN')") |
#[pre_authorize(roles = ["A", "B"])] | @PreAuthorize("hasAnyRole('A', 'B')") |
#[pre_authorize(authority = "read")] | @PreAuthorize("hasAuthority('read')") |
#[pre_authorize(authorities = ["r", "w"])] | @PreAuthorize("hasAnyAuthority('r', 'w')") |
§Usage
ⓘ
use actix_security_core::http::security::AuthenticatedUser;
use actix_security_codegen::pre_authorize;
// Check authentication only
#[pre_authorize(authenticated)]
#[get("/protected")]
async fn protected(user: AuthenticatedUser) -> impl Responder {
HttpResponse::Ok().body("Protected")
}
// Check single role
#[pre_authorize(role = "ADMIN")]
#[get("/admin")]
async fn admin(user: AuthenticatedUser) -> impl Responder {
HttpResponse::Ok().body("Admin")
}
// Check multiple roles (OR logic)
#[pre_authorize(roles = ["ADMIN", "MANAGER"])]
#[get("/management")]
async fn management(user: AuthenticatedUser) -> impl Responder {
HttpResponse::Ok().body("Management")
}
// Check authority
#[pre_authorize(authority = "users:read")]
#[get("/api/users")]
async fn get_users(user: AuthenticatedUser) -> impl Responder {
HttpResponse::Ok().body("Users")
}
// Check multiple authorities (OR logic)
#[pre_authorize(authorities = ["users:read", "users:write"])]
#[get("/api/users/manage")]
async fn manage_users(user: AuthenticatedUser) -> impl Responder {
HttpResponse::Ok().body("Manage users")
}