< Summary

Information
Class: ArturRios.Util.WebApi.Security.Authentication.TokenExtractor
Assembly: ArturRios.Util.WebApi
File(s): D:\Repositories\dotnet-webapi-util\src\Security\Authentication\TokenExtractor.cs
Line coverage
95%
Covered lines: 22
Uncovered lines: 1
Coverable lines: 23
Total lines: 47
Line coverage: 95.6%
Branch coverage
88%
Covered branches: 16
Total branches: 18
Branch coverage: 88.8%
Method coverage
100%
Covered methods: 3
Fully covered methods: 0
Total methods: 3
Method coverage: 100%
Full method coverage: 0%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Extract(...)75%8890%
FromHeader(...)100%88100%
FromCookie(...)100%22100%

File(s)

D:\Repositories\dotnet-webapi-util\src\Security\Authentication\TokenExtractor.cs

#LineLine coverage
 1using System.Net.Http.Headers;
 2using ArturRios.Util.WebApi.Security.Enums;
 3using Microsoft.AspNetCore.Http;
 4
 5namespace ArturRios.Util.WebApi.Security.Authentication;
 6
 7/// <summary>Reads the raw authentication token from an <see cref="HttpContext"/> according to a <see cref="TokenSource"
 8public static class TokenExtractor
 9{
 10    /// <summary>Extracts the token from the header, the named cookie, or either (header first), returning <see cref="st
 11    /// <param name="context">The current HTTP context.</param>
 12    /// <param name="source">Where to read the token from.</param>
 13    /// <param name="cookieName">The cookie name used when <paramref name="source"/> is <see cref="TokenSource.Cookie"/>
 14    public static string Extract(HttpContext context, TokenSource source, string cookieName)
 1515    {
 1516        ArgumentNullException.ThrowIfNull(context);
 17
 1518        return source switch
 1519        {
 820            TokenSource.Header => FromHeader(context),
 421            TokenSource.Cookie => FromCookie(context, cookieName),
 322            TokenSource.Either => FromHeader(context) is { Length: > 0 } header ? header : FromCookie(context, cookieNam
 023            _ => string.Empty
 1524        };
 1525    }
 26
 27    private static string FromHeader(HttpContext context)
 1128    {
 1129        var header = context.Request.Headers.Authorization.FirstOrDefault();
 30
 1131        if (string.IsNullOrWhiteSpace(header) || !AuthenticationHeaderValue.TryParse(header, out var parsed) ||
 1132            !string.Equals(parsed.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) ||
 1133            string.IsNullOrWhiteSpace(parsed.Parameter))
 434        {
 435            return string.Empty;
 36        }
 37
 738        return parsed.Parameter.Trim();
 1139    }
 40
 41    private static string FromCookie(HttpContext context, string cookieName)
 642    {
 643        var value = context.Request.Cookies[cookieName];
 44
 645        return string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim();
 646    }
 47}