< Summary

Information
Class: ArturRios.Util.WebApi.Security.Filters.RoleRequirementFilter
Assembly: ArturRios.Util.WebApi
File(s): /home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Security/Filters/RoleRequirementFilter.cs
Line coverage
100%
Covered lines: 10
Uncovered lines: 0
Coverable lines: 10
Total lines: 39
Line coverage: 100%
Branch coverage
100%
Covered branches: 6
Total branches: 6
Branch coverage: 100%
Method coverage
100%
Covered methods: 2
Fully covered methods: 2
Total methods: 2
Method coverage: 100%
Full method coverage: 100%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
OnAuthorization(...)100%66100%

File(s)

/home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Security/Filters/RoleRequirementFilter.cs

#LineLine coverage
 1using ArturRios.Extensions;
 2using ArturRios.Util.WebApi.Security.Attributes;
 3using ArturRios.Util.WebApi.Security.Extensions;
 4using Microsoft.AspNetCore.Mvc.Filters;
 5
 6namespace ArturRios.Util.WebApi.Security.Filters;
 7
 8/// <summary>Authorization filter that rejects requests with a 403 response unless the authenticated user's role
 9/// is one of <paramref name="authorizedRoles"/>, or with a 401 response when no user is authenticated. Applied
 10/// declaratively via <see cref="Attributes.RoleRequirementAttribute"/>, unless the action is marked with
 11/// <see cref="AllowAnonymousAttribute"/>.</summary>
 12/// <param name="authorizedRoles">The role values permitted to access the resource.</param>
 713public class RoleRequirementFilter(params int[] authorizedRoles) : IAuthorizationFilter
 14{
 15    /// <summary>Checks the authenticated user's role against the authorized roles and short-circuits the pipeline
 16    /// with a 401 result when there is no user, or a 403 result when the role does not match.</summary>
 17    /// <param name="context">The authorization filter context for the current request.</param>
 18    public void OnAuthorization(AuthorizationFilterContext context)
 19    {
 720        if (context.ActionDescriptor.AllowsAnonymous())
 21        {
 222            return;
 23        }
 24
 525        var user = context.HttpContext.GetUser();
 26
 527        if (user is null)
 28        {
 129            context.Result = AuthorizationResults.Unauthorized();
 30
 131            return;
 32        }
 33
 434        if (!user.RoleId.In(authorizedRoles))
 35        {
 236            context.Result = AuthorizationResults.Forbidden();
 37        }
 438    }
 39}