TaskHub.Shared

Security & Identity Usage

TaskHub.Shared simplifies authentication and authorization by providing a pre-configured JWT-based identity system.

Configuration

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
}

Registration

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);

Accessing the Current User

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"))
        {
            // ...
        }
    }
}

Protecting Your API

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 { ... }

Internal Middleware: UserStatusMiddleware

The UserStatusMiddleware is automatically added to the pipeline. Its role is to:

  1. Validate Token: Ensure the JWT is present and valid.
  2. Enrich Context: Extract claims (like User ID and Roles) and populate the IUserService instance for the current scope.
  3. Status Check: (Optional) Perform additional checks, such as verifying if the user account is active in the database.

Roles & Permissions

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.