Documentation Menu
Spark utilizes role based authorization and it is already scaffolded for you.
Spark’s authorization is setup for you in AppServiceRegistration.AddAppServices()
.
services.AddAuthorization(config, new string[] { CustomRoles.Admin, CustomRoles.User });
Every Spark app comes with a Role
model in the Application/Models
directory. Roles can control what pages logged in users see. A user can be assigned a role through the UserRole
relationship.
public class Role : BaseModel
{
public Role()
{
UserRoles = new HashSet<UserRole>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
By default, a Spark app comes with 2 roles out of the box. Admin
and User
.
public static class CustomRoles
{
public const string Admin = nameof(Admin);
public const string User = nameof(User);
}
You can add more custom roles if needed.
First, add the new custom role to the Application/Models/CustomRoles.cs
class.
public static class CustomRoles
{
public const string Admin = nameof(Admin);
public const string User = nameof(User);
public const string NewRole = nameof(NewRole);
}
Second, add the new custom role record to the Roles
database table.
The easiest way to do this is utilizing the OnModelCreating
method in the DatabaseContext
class. In it, you can make entity framework insert the record when running a migration.
Spark does this for you already with the Admin and User roles. Just add your new Role as a new entry.
protected override void OnModelCreating(ModelBuilder builder) {
...
builder.Entity<Role>().HasData(
new Role { Id = 1, Name = CustomRoles.User },
new Role { Id = 2, Name = CustomRoles.Admin },
new Role { Id = 3, Name = CustomRoles.NewRole }
);
}
Finally, add the custom role when Spark registers authorization in AppServiceRegistration.AddAppServices()
.
...
services.AddAuthorization(config, new string[] {
CustomRoles.Admin,
CustomRoles.User,
CustomRoles.NewRole
});
...
You can use Roles to determine what type of users can access what content. Simply use the Authorize
attribute and pass in a custom role as a Policy.
@page "/admin/dashboard"
@attribute [Authorize(Roles = CustomRoles.Admin)]
<section>
<h1>
Admin Dashboard
</h1>
</section>