Authenticated routes and policies | laravel-permission-rust | Spatie       

 SPATIE  

laravel-permission-rust
=======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-permission-rust](https://spatie.be/docs/laravel-permission-rust/v1)  Authenticated routes and policies

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-permission-rust/v1) 

  Authenticated routes and policies    
- [ Introduction ](https://spatie.be/docs/laravel-permission-rust/v1/introduction)
- [ Install and connect the application ](https://spatie.be/docs/laravel-permission-rust/v1/installation-laravel)
- [ Roles and permissions ](https://spatie.be/docs/laravel-permission-rust/v1/basic-usage)
- [ Authenticated routes and policies ](https://spatie.be/docs/laravel-permission-rust/v1/authorization)
- [ Querying users and bulk assignment ](https://spatie.be/docs/laravel-permission-rust/v1/querying-users)
- [ Console commands ](https://spatie.be/docs/laravel-permission-rust/v1/commands)
- [ Custom models and IDs ](https://spatie.be/docs/laravel-permission-rust/v1/models-and-ids)
- [ Cache and events ](https://spatie.be/docs/laravel-permission-rust/v1/cache-and-events)
- [ Integration tests ](https://spatie.be/docs/laravel-permission-rust/v1/testing)

 Authenticated routes and policies
=================================

Authenticated routes and policies
===========================================================================================================================================================

Use Laravel's real `routing.web`, session provider and `Authenticate` middleware. The package middleware asks the request for its authenticated model; it does not accept a user ID header. This route example compiles with the same account model as the installation page:

```
use laravel::{Application, auth::{Authenticatable, Authenticate, RememberToken}, hash::PasswordHash, model::model};
use spatie_permission::{MiddlewareKind, PermissionMiddleware, PermissionRegistrar};

Application::configure().with_routing(|routing, _| {
    routing.web(|route| {
        route.middleware(Authenticate).group(|route| {
            route.get("/articles", || async { "Articles" }).middleware(
                PermissionMiddleware::<Account>::new(
                    PermissionRegistrar::default(), MiddlewareKind::Permission, ["edit articles"],
                )
            );
        });
    });
});
```

`Role`, `Permission` and `RoleOrPermission` are OR checks over their supplied names. An empty list denies. Stack middleware to require several independent conditions. `.guard("api")`selects the grant namespace, not authentication. `.team(17)` is a fixed, application-validated route context; for dynamic teams, validate membership in application middleware and construct the corresponding `Subject` in the handler/policy. Guests receive 401 unless the application's native login-page configuration redirects them. Authenticated denials are 403.

Integrate permission checks in a typed policy method and let Laravel enforce its result:

```
use laravel::{auth::{Authenticatable, RememberToken, policy}, hash::PasswordHash, http::Request, model::model};
use spatie_permission::PermissionRegistrar;

pub struct ArticlePolicy;

#[policy]
impl ArticlePolicy {
    fn before(user: &Account) -> Option<bool> { user.super_admin.then_some(true) }

    pub async fn edit(user: &Account) -> laravel::Result<bool> {
        let registrar = laravel::resolve::<PermissionRegistrar>().await?;
        registrar.for_model(user)?.check_permission_to("edit articles").await
    }
}

async fn edit(request: Request) -> laravel::Result<&'static str> {
    request.authorize(ArticlePolicy::edit, ()).await?;
    Ok("Allowed")
}
```

Install the package provider as shown in the installation page. The policy's `before` override applies only to that policy. Role/permission middleware remains an exact grant check and does not silently inherit a global super-admin bypass. The framework's `request.can`and the user's `Authorizable::can` accept these same typed methods.

Required role/permission names are hidden in middleware errors by default. Opt in using `display_role_in_exception` or `display_permission_in_exception`. `RoleOrPermission` requires both flags before revealing its shared list, so enabling one never discloses the other kind.

Use native policies, `RequestGuard`/`Authenticate::via`, and explicitly computed template data to authorize requests and render controls. Applications may attach native queued listeners to package assignment events.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
