Authorization
- Introduction
- Complete Example: Owner-Only Updates
- Gates
- Creating Policies
- Writing Policies
- Authorizing Actions Using Policies
Introduction
Besides authentication, DotBlaze gives you Laravel's two ways to decide whether a user may perform an action: gates, closures for actions not tied to a model, and policies, classes that group the rules for one model. Checks are asynchronous (policies may query the database) and run for the logged-in user; a denied check in a controller or route becomes a 403 response.
DotBlaze's Gate is its own registry. It does not use ASP.NET Core's IAuthorizationService or [Authorize] policies.
Gates
Writing Gates
Define gates in a provider's Boot method. The first type argument is your user model; guests are denied without calling the closure:
public override void Boot(WebApplication app)
{
Gate.Define<User>("view-reports", user => user.IsAdmin);
Gate.Define<User, Team>("manage-team", (user, team) => team.OwnerId == user.Id);
Gate.Define<User, Team>("leave-team", async (user, team) =>
await TeamMember.Where(m => m.TeamId == team.Id).Count() > 1);
}Authorizing Actions
if (await Gate.Allows("view-reports")) { ... }
if (await Gate.Denies("manage-team", team)) { ... }
await Gate.Authorize("manage-team", team); // throws AuthorizationException → 403
await Gate.ForUser(otherUser).Allows("view-reports"); // another user (null = guest)An ability that is not defined is denied. AuthorizationException thrown anywhere in a request becomes a 403 response (JSON { "message": ... } when the request wants JSON).
Intercepting Gate Checks
Gate.Before runs before every check. Return true or false to decide, or null to continue:
Gate.Before((user, ability) => user is User { IsAdmin: true } ? true : null);Creating Policies
Generating Policies
dotblaze make:policy PostPolicy
dotblaze make:policy PhotoPolicy --model=ImagePolicies live in app/Policies.
Policy Discovery
A class that extends Policy<TModel> is found automatically in your application, so PostPolicy : Policy<Post> handles every check whose first argument is a Post. To register one explicitly (for example a policy in another assembly):
Gate.Policy<Post, PostPolicy>();Writing Policies
Policy Methods
Each ability is a public method that takes the user, then the model, and returns bool or Task<bool>. From the sample app:
using SampleApp.Models;
namespace SampleApp.Policies;
public class PostPolicy : Policy<Post>
{
public bool Update(User user, Post post) => post.UserId == user.Id;
public bool Delete(User user, Post post) => post.UserId == user.Id;
}The ability name matches the method name ignoring case, dashes, and underscores: "update" → Update, "view-any" → ViewAny. A policy without a matching method denies. Policies are created per check through dependency injection, so the constructor can take services.
Methods Without Models
For abilities like create there is no instance yet: pass the model type, and the method takes only the user:
public bool Create(User user) => user.EmailVerifiedAt is not null;await Gate.Authorize("create", typeof(Post));Guest Users
Guests are denied unless the user parameter is nullable:
public bool View(User? user, Post post) => post.Published || user?.Id == post.UserId;Policy Filters
A Before(User user, string ability) method returning bool? runs before the other methods of that policy:
public bool? Before(User user, string ability) => user.IsAdmin ? true : null;Authorizing Actions Using Policies
In Controllers
BaseController.Authorize is Laravel's $this->authorize(): it throws AuthorizationException, which becomes a 403. From the sample's PostController:
public async Task<IActionResult> Edit(Post post)
{
await Authorize("update", post);
return View(post);
}
public async Task<IActionResult> Destroy(Post post)
{
await Authorize("delete", post);
await post.Delete();
return RedirectRoute("posts.index").With("status", "Post deleted.");
}On Routes
.Can(ability, parameters...) authorizes before the action runs, after route model binding, passing the named action parameters:
Route.Get<PostController>("/posts/{post}/edit", c => c.Edit).Can("update", "post");
Route.Post<PostController>("/posts", c => c.Store).Can<Post>("create"); // PostPolicy.Create(user)A denied check returns 403 without running the action. route:list shows the abilities.
In Views
@if (await Can("update", Model))
{
<a href="@Route("posts.edit", new { post = Model.Id })">Edit</a>
}
@if (await Cannot("delete", Model)) { ... }Complete Example: Owner-Only Updates
The walkthrough's PostPolicy and controller define a complete ownership policy. The policy compares the authenticated user's key with the persisted Post.UserId, and the controller authorizes before modifying the row.
Use this Blade markup in its post detail view:
@can('update', Model)
<a href="{{ Route('posts.edit', new { post = Model.Id }) }}">Edit this post</a>
@endcanRun the complete HTTP test:
dotnet test Blog.Tests --filter FullyQualifiedName~PostTestIt creates an owner and a second user, verifies the second user's PUT and DELETE return 403, then proves the original data remains. A hidden link is not authorization; keep the action's await Authorize("update", post) even when using @can. For tenant-private reads, also add a read policy or owner-scoped query; the tutorial intentionally allows signed-in users to read all posts.