< Summary

Information
Class: ArturRios.Util.WebApi.Security.Attributes.AuthorizeAttribute
Assembly: ArturRios.Util.WebApi
File(s): D:\Repositories\dotnet-webapi-util\src\Security\Attributes\AuthorizeAttribute.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 12
Coverable lines: 12
Total lines: 32
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 4
Branch coverage: 0%
Method coverage
0%
Covered methods: 0
Fully covered methods: 0
Total methods: 1
Method coverage: 0%
Full method coverage: 0%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
OnAuthorization(...)0%2040%

File(s)

D:\Repositories\dotnet-webapi-util\src\Security\Attributes\AuthorizeAttribute.cs

#LineLine coverage
 1using ArturRios.Util.WebApi.Security.Records;
 2using Microsoft.AspNetCore.Http;
 3using Microsoft.AspNetCore.Mvc;
 4using Microsoft.AspNetCore.Mvc.Filters;
 5
 6namespace ArturRios.Util.WebApi.Security.Attributes;
 7
 8/// <summary>Rejects requests with a 401 response unless an <see cref="AuthenticatedUser"/> was attached to the
 9/// context (typically by <see cref="Security.Middleware.AuthenticationMiddleware"/>), unless the action is marked with 
 10[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
 11public class AuthorizeAttribute : Attribute, IAuthorizationFilter
 12{
 13    /// <summary>Checks for an authenticated user on the context and short-circuits the pipeline with a 401 result if no
 14    /// <param name="context">The authorization filter context for the current request.</param>
 15    public void OnAuthorization(AuthorizationFilterContext context)
 016    {
 017        var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
 18
 019        if (allowAnonymous)
 020        {
 021            return;
 22        }
 23
 024        var user = (AuthenticatedUser?)context.HttpContext.Items["User"];
 25
 026        if (user is null)
 027        {
 028            context.Result =
 029                new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
 030        }
 031    }
 32}