1
0
mirror of https://github.com/Radarr/Radarr.git synced 2026-03-28 18:05:41 -04:00
Files
Radarr/src/Radarr.Http/Authentication/ApiKeyAuthenticationHandler.cs
ta264 06e2d5b3c3 New: Use native dotnet host and DryIoc
(cherry picked from commit d6170dbfedf27a6218afe242a0fae2eb8b368aec)
(cherry picked from commit 7fe36a7e9222e830f4920e09a85115df0bdbf190)
2021-10-25 13:45:44 -04:00

94 lines
3.0 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NzbDrone.Core.Configuration;
namespace Radarr.Http.Authentication
{
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
{
public const string DefaultScheme = "API Key";
public string Scheme => DefaultScheme;
public string AuthenticationType = DefaultScheme;
public string HeaderName { get; set; }
public string QueryName { get; set; }
}
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private readonly string _apiKey;
public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeyAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IConfigFileProvider config)
: base(options, logger, encoder, clock)
{
_apiKey = config.ApiKey;
}
private string ParseApiKey()
{
// Try query parameter
if (Request.Query.TryGetValue(Options.QueryName, out var value))
{
return value.FirstOrDefault();
}
// No ApiKey query parameter found try headers
if (Request.Headers.TryGetValue(Options.HeaderName, out var headerValue))
{
return headerValue.FirstOrDefault();
}
return Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var providedApiKey = ParseApiKey();
if (string.IsNullOrWhiteSpace(providedApiKey))
{
return Task.FromResult(AuthenticateResult.NoResult());
}
if (_apiKey == providedApiKey)
{
var claims = new List<Claim>
{
new Claim("ApiKey", "true")
};
var identity = new ClaimsIdentity(claims, Options.AuthenticationType);
var identities = new List<ClaimsIdentity> { identity };
var principal = new ClaimsPrincipal(identities);
var ticket = new AuthenticationTicket(principal, Options.Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
return Task.FromResult(AuthenticateResult.NoResult());
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.StatusCode = 401;
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = 403;
return Task.CompletedTask;
}
}
}