API reference — Security
Nuvora.Nexus.Relay.Auth
Authentication and authorization module for Nuvora Nexus Relay
dotnet add package Nuvora.Nexus.Relay.Auth
Nuvora.Nexus.Relay.Auth
ApplicationBuilderExtensions
public static class ApplicationBuilderExtensions
Extension methods for wiring Relay authorization into the ASP.NET Core request pipeline.
Methods
static IApplicationBuilder UseRelayAuthContext(this IApplicationBuilder app)
Adds the RelayAuthorizationMiddleware, which projects the authenticated ClaimsPrincipal onto the framework’s AuthContext.
AuthContext
public class AuthContext
Represents the current authentication context available throughout the pipeline
Properties
Guid? UserId { get; init; }
The authenticated user’s ID, null if not authenticated
IReadOnlyCollection<string> Roles { get; init; }
The user’s roles
IReadOnlyDictionary<string, IReadOnlyList<string>> ClaimValues { get; init; }
All claim values grouped by claim type — the authoritative, multi-valued claim store. Keys are compared case-insensitively. A claim type may map to several values (e.g. one entry per granted permission).
IReadOnlyDictionary<string, string> Claims { get; init; }
The user’s claims, one value per claim type. This is a single-valued view kept for convenience and backward compatibility; when a claim type carries multiple values (e.g. several permission claims) this exposes only the first. Use AuthContext.GetClaimValues / AuthContext.ClaimValues to see every value.
bool IsAuthenticated { get; }
Indicates whether the user is authenticated
static AuthContext Unauthenticated { get; }
Creates an unauthenticated context
string? Username { get; init; }
The authenticated user’s username, null if not authenticated
Methods
IReadOnlyList<string> GetClaimValues(string claimType)
Returns every value of the given claim type (empty if the type is absent). Falls back to the single-valued AuthContext.Claims view for contexts built without AuthContext.ClaimValues.
bool HasAllRoles(params string[] roles)
Checks if the user has all of the specified roles
bool HasAnyRole(params string[] roles)
Checks if the user has any of the specified roles
bool HasClaim(string claimType, string? claimValue = null)
Checks if the user has the specified claim. When claimValue is supplied, the match is made against all values of the claim type, so multi-valued claims (e.g. several permission claims) are handled correctly.
bool HasPermission(string permission)
Checks if the user has the specified permission Permissions are typically stored as claims with type “permission”
bool HasRole(string role)
Checks if the user has the specified role
static AuthContext Create(Guid userId, string username, IEnumerable<string>? roles = null, IDictionary<string, string>? claims = null)
Creates an authenticated context from single-valued claims.
static AuthContext Create(Guid userId, string username, IEnumerable<string>? roles, IEnumerable<KeyValuePair<string, string>>? claims)
Creates an authenticated context from claims that may repeat a claim type. Claims are grouped by type into multi-valued entries; AuthContext.Claims exposes the first value of each type.
AuthContextAccessor
public class AuthContextAccessor : IAuthContextAccessor
AsyncLocal-based implementation of IAuthContextAccessor for thread-safe context propagation
Properties
AuthContext Current { get; }
Gets the current authentication context, or an unauthenticated context if none is set
Methods
void SetContext(AuthContext context)
Sets the current authentication context
IAuthContextAccessor
public interface IAuthContextAccessor
Provides access to the current authentication context
Properties
AuthContext Current { get; }
Gets the current authentication context
Methods
void SetContext(AuthContext context)
Sets the current authentication context
RelayAuthOptions
public sealed class RelayAuthOptions
Configuration for the RelayAuthorizationMiddleware, which bridges the ASP.NET Core authenticated principal (ClaimsPrincipal) into the framework’s AuthContext. Authentication itself (token validation) is performed by ASP.NET Core authentication (e.g. AddAuthentication().AddJwtBearer()); this middleware only maps the resulting claims so the command/query authorization behaviors can enforce [RequireRole]/[RequirePermission]/[RequireClaim]/[RequirePolicy].
Properties
IReadOnlyList<string> RoleClaimTypes { get; set; }
Claim types treated as roles. All matching claim values across these types are collected into AuthContext.Roles.
IReadOnlyList<string> UserIdClaimTypes { get; set; }
Claim types inspected, in order, to resolve the user id. The first present value that parses as a Guid wins. Defaults cover the common JWT (sub) and WS-* (nameidentifier) conventions. AuthContext keys identity on a Guid, so a non-Guid id cannot be represented and the request is treated as unauthenticated (a warning is logged).
IReadOnlyList<string> UsernameClaimTypes { get; set; }
Claim types inspected, in order, to resolve the username. Falls back to IIdentity.Name when none are present.
bool RequireAuthenticatedUser { get; set; }
When true, the middleware short-circuits with 401 for any request that arrives without an authenticated principal. Off by default: authentication failures and per-endpoint requirements are normally surfaced by ASP.NET Core authentication and the per-message authorization behaviors, so that [AllowAnonymous] endpoints (health checks, sign-in, etc.) still flow through. Enable only when you want the entire HTTP surface gated.
ServiceCollectionExtensions
public static class ServiceCollectionExtensions
Extension methods for registering authentication and authorization services
Methods
static IServiceCollection AddAuthorizationPolicy<TPolicy>(this IServiceCollection services)
Adds a custom authorization policy. The policy is referenced from [RequirePolicy("...")] attributes by its IAuthorizationPolicy.Name.
static IServiceCollection AddAuthorizationPolicy<TPolicy>(this IServiceCollection services, TPolicy policyInstance)
Adds a custom authorization policy instance. The policy is referenced from [RequirePolicy("...")] attributes by its IAuthorizationPolicy.Name.
static IServiceCollection AddRelayAuth(this IServiceCollection services, Action<RelayAuthOptions>? configure = null)
Adds Relay authentication and authorization services to the service collection
Nuvora.Nexus.Relay.Auth.Attributes
AllowAnonymousAttribute
public class AllowAnonymousAttribute : Attribute
Marks a command or query as allowing anonymous access, bypassing all authorization checks
RequireAuthenticationAttribute
public class RequireAuthenticationAttribute : Attribute
Marks a command or query as requiring authentication (any authenticated user)
RequireClaimAttribute
public class RequireClaimAttribute : Attribute
Marks a command or query as requiring the user to have the specified claim
Constructors
RequireClaimAttribute(string claimType)
Initializes a new instance with the specified claim type
RequireClaimAttribute(string claimType, string claimValue)
Initializes a new instance with the specified claim type and value
Properties
string ClaimType { get; }
The claim type that the user must have
string? ClaimValue { get; }
The claim value that the user must have (optional)
RequirePermissionAttribute
public class RequirePermissionAttribute : Attribute
Marks a command or query as requiring the user to have the specified permission
Constructors
RequirePermissionAttribute(string permission)
Initializes a new instance with the specified permission
Properties
string Permission { get; }
The permission that the user must have
RequirePolicyAttribute
public class RequirePolicyAttribute : Attribute
Marks a command or query as requiring the specified authorization policy to be satisfied
Constructors
RequirePolicyAttribute(string policyName)
Initializes a new instance with the specified policy name
Properties
string PolicyName { get; }
The name of the policy that must be satisfied
RequireRoleAttribute
public class RequireRoleAttribute : Attribute
Marks a command or query as requiring the user to have any of the specified roles
Constructors
RequireRoleAttribute(params string[] roles)
Initializes a new instance with the specified roles
Properties
string[] Roles { get; }
The roles that the user must have (any one of them)
Nuvora.Nexus.Relay.Auth.Authorization
AuthorizationResult
public class AuthorizationResult
Represents the result of an authorization policy evaluation
Properties
bool Succeeded { get; }
Indicates whether the authorization was successful
string? FailureReason { get; }
The reason for authorization failure, if applicable
Methods
static AuthorizationResult Fail(string reason)
Creates a failed authorization result with the specified reason
static AuthorizationResult Success()
Creates a successful authorization result
AuthorizationService
public class AuthorizationService
Shared service for performing authorization checks on commands and queries. All authorization attributes on a message are evaluated — [RequireAuthentication] is one requirement among the others, not a short-circuit, so combining it with [RequireRole]/[RequirePermission]/… enforces every declared requirement.
Constructors
AuthorizationService(IAuthContextAccessor authContextAccessor, IAuthorizationPolicyProvider policyProvider, ILogger<AuthorizationService> logger)
Properties
AuthContext AuthContext { get; }
Gets the current authentication context
Methods
Task AuthorizeAsync(Type type, string typeName, string itemName, Func<string, CancellationToken, Task<AuthorizationResult>>? evaluatePolicyAsync = null, CancellationToken cancellationToken = default(CancellationToken))
Performs authorization checks on a type
DefaultAuthorizationPolicyProvider
public class DefaultAuthorizationPolicyProvider : IAuthorizationPolicyProvider
Default IAuthorizationPolicyProvider: resolves all registered IAuthorizationPolicy instances from DI and indexes them by IAuthorizationPolicy.Name.
Constructors
DefaultAuthorizationPolicyProvider(IServiceProvider serviceProvider)
Methods
IAuthorizationPolicy GetPolicy(string policyName)
Gets an authorization policy by name
IAuthorizationPolicy
public interface IAuthorizationPolicy
Interface for custom authorization policies
Properties
string Name { get; }
The unique name this policy is referenced by from [RequirePolicy("...")] attributes
Methods
Task<AuthorizationResult> EvaluateCommandAsync<TCommand, TResponse>(AuthContext authContext, TCommand command, CancellationToken cancellationToken = default(CancellationToken))
Evaluates the authorization policy for a command with response
Task<AuthorizationResult> EvaluateQueryAsync<TQuery, TResponse>(AuthContext authContext, TQuery query, CancellationToken cancellationToken = default(CancellationToken))
Evaluates the authorization policy for a query
Task<AuthorizationResult> EvaluateVoidCommandAsync<TCommand>(AuthContext authContext, TCommand command, CancellationToken cancellationToken = default(CancellationToken))
Evaluates the authorization policy for a void command
IAuthorizationPolicyProvider
public interface IAuthorizationPolicyProvider
Provides access to authorization policies by name
Methods
IAuthorizationPolicy GetPolicy(string policyName)
Gets an authorization policy by name
Nuvora.Nexus.Relay.Auth.Behaviors
AuthorizationBehavior<TCommand, TResponse>
public class AuthorizationBehavior<TCommand, TResponse> : ICommandPipelineBehavior<TCommand, TResponse> where TCommand : ICommand<TResponse>
Pipeline behavior for command authorization (with response)
Constructors
AuthorizationBehavior(AuthorizationService authorizationService, IAuthorizationPolicyProvider policyProvider)
Methods
Task<TResponse> Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task<TResponse>> next)
AuthorizationBehavior<TCommand>
public class AuthorizationBehavior<TCommand> : ICommandPipelineBehavior<TCommand> where TCommand : ICommand
Pipeline behavior for command authorization (void commands)
Constructors
AuthorizationBehavior(AuthorizationService authorizationService, IAuthorizationPolicyProvider policyProvider)
Methods
Task Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task> next)
QueryAuthorizationBehavior<TQuery, TResponse>
public class QueryAuthorizationBehavior<TQuery, TResponse> : IQueryPipelineBehavior<TQuery, TResponse> where TQuery : IQuery<TResponse>
Pipeline behavior for query authorization
Constructors
QueryAuthorizationBehavior(AuthorizationService authorizationService, IAuthorizationPolicyProvider policyProvider)
Methods
Task<TResponse> Handle(TQuery query, CancellationToken cancellationToken, Func<TQuery, CancellationToken, Task<TResponse>> next)
Nuvora.Nexus.Relay.Auth.Exceptions
ForbiddenException
public class ForbiddenException : Exception
Exception thrown when a user is authenticated but lacks the required permissions.
This type is intentionally duplicated in Nuvora.Nexus.Relay.Web.Exceptions: the Web package cannot depend on the Auth package (it would drag in the Relay/Core dependency graph), so Web’s DefaultExceptionMapper matches this Auth exception by its full type name and maps it to HTTP 403 Forbidden. Renaming or moving this type breaks that mapping.
Constructors
ForbiddenException()
ForbiddenException(string message)
ForbiddenException(string message, Exception innerException)
UnauthorizedException
public class UnauthorizedException : Exception
Exception thrown when a user is not authenticated but authentication is required.
This type is intentionally duplicated in Nuvora.Nexus.Relay.Web.Exceptions: the Web package cannot depend on the Auth package (it would drag in the Relay/Core dependency graph), so Web’s DefaultExceptionMapper matches this Auth exception by its full type name and maps it to HTTP 401 Unauthorized. Renaming or moving this type breaks that mapping.
Constructors
UnauthorizedException()
UnauthorizedException(string message)
UnauthorizedException(string message, Exception innerException)
Nuvora.Nexus.Relay.Auth.Middleware
RelayAuthorizationMiddleware
public sealed class RelayAuthorizationMiddleware
Bridges the ASP.NET Core authenticated principal (HttpContext.User) into the framework’s AuthContext so the command/query authorization behaviors can enforce authorization.
This middleware does not validate credentials itself — token/cookie validation is the job of ASP.NET Core authentication (e.g. AddAuthentication().AddJwtBearer() + UseAuthentication()), which must run before this middleware. Its sole responsibility is to project the already-validated ClaimsPrincipal onto an AuthContext and publish it via IAuthContextAccessor. Per-message requirements ([RequireAuthentication], [RequireRole], …) are then enforced downstream by the authorization pipeline behaviors, which surface UnauthorizedException (401) / ForbiddenException (403).
Constructors
RelayAuthorizationMiddleware(RequestDelegate next, ILogger<RelayAuthorizationMiddleware> logger, RelayAuthOptions? options = null)
Methods
Task InvokeAsync(HttpContext context)