TaskHub.Shared simplifies authentication and authorization by providing a pre-configured JWT-based identity system.
Define your JWT settings in appsettings.json.
"Jwt": {
"Issuer": "TaskHub",
"Audience": "TaskHub-Users",
"Key": "your-super-secret-key-that-is-at-least-32-chars-long",
"ExpiryInMinutes": 60
}
The identity system is registered automatically when using FullHostBuilder. If you need to register it manually:
using TaskHub.Shared.Authorization.Identity.Bootstrap;
builder.Services.AddAppAuthorization(builder.Configuration.GetSection("Jwt").Bind);
Inject IUserService to access information about the currently authenticated user. This interface is scoped to the current request.
public class MyService(IUserService userService)
{
public void DoSomething()
{
var userId = userService.UserId;
var roles = userService.Roles;
if (userService.IsInRole("Admin"))
{
// ...
}
}
}
Use the standard [Authorize] attribute on your controllers or actions.
[Authorize]
[ApiVersion("1.0")]
[Route("v{version:apiVersion}/my-protected-resource")]
public class MyController : ControllerBase { ... }
The UserStatusMiddleware is automatically added to the pipeline. Its role is to:
IUserService instance for the current scope.TaskHub uses a claims-based approach. Roles are stored in the role claim of the JWT. You can define your own roles and use them in the [Authorize(Roles = "Admin")] attribute or check them via IUserService.