< Summary

Information
Class: LGDXRobotCloud.API.Authentication.ApiKeyAuthenticationSchemeHandler
Assembly: LGDXRobotCloud.API
File(s): /builds/yukaitung/lgdxrobot2-cloud/LGDXRobotCloud.API/Authentication/ApiKeyAuthenticationSchemeHandler.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 16
Coverable lines: 16
Total lines: 37
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 10
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%2040%
HandleAuthenticateAsync()0%4260%

File(s)

/builds/yukaitung/lgdxrobot2-cloud/LGDXRobotCloud.API/Authentication/ApiKeyAuthenticationSchemeHandler.cs

#LineLine coverage
 1using System.Security.Claims;
 2using System.Text.Encodings.Web;
 3using LGDXRobotCloud.API.Services.Administration;
 4using Microsoft.AspNetCore.Authentication;
 5using Microsoft.Extensions.Options;
 6
 7namespace LGDXRobotCloud.API.Authentication;
 8
 9public class ApiKeyAuthenticationSchemeHandler(
 10    IOptionsMonitor<ApiKeyAuthenticationSchemeOptions> options,
 11    ILoggerFactory logger,
 12    UrlEncoder encoder,
 13    IApiKeyService apiKeyService,
 14    IWebHostEnvironment webHostEnvironment
 015  ) : AuthenticationHandler<ApiKeyAuthenticationSchemeOptions>(options, logger, encoder)
 16{
 017  private readonly IApiKeyService _apiKeyService = apiKeyService ?? throw new ArgumentNullException(nameof(apiKeyService
 018  private readonly IWebHostEnvironment _webHostEnvironment = webHostEnvironment ?? throw new ArgumentNullException(nameo
 19
 20
 21  protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
 022  {
 023    if (!_webHostEnvironment.IsDevelopment())
 024    {
 025      var apiKey = Context.Request.Headers["X-API-KEY"];
 026      if (string.IsNullOrWhiteSpace(apiKey) || await _apiKeyService.ValidateApiKeyAsync(apiKey!) == false)
 027      {
 028        return AuthenticateResult.Fail("X-API-KEY is invalid");
 29      }
 030    }
 31
 032    var identity = new ClaimsIdentity([], Scheme.Name);
 033    var principal = new ClaimsPrincipal(identity);
 034    var ticket = new AuthenticationTicket(principal, Scheme.Name);
 035    return AuthenticateResult.Success(ticket);
 036  }
 37}