wabbajack/Wabbajack.Server/ApiKeyAuthorizationHandler.cs

143 lines
4.8 KiB
C#
Raw Normal View History

2020-05-09 22:16:16 +00:00
using System;
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.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2021-09-27 12:42:46 +00:00
using Wabbajack.DTOs.JsonConverters;
2020-05-09 22:16:16 +00:00
using Wabbajack.Server.DataLayer;
2020-06-14 13:13:29 +00:00
using Wabbajack.Server.DTOs;
2021-02-18 05:44:54 +00:00
using Wabbajack.Server.Services;
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
namespace Wabbajack.BuildServer;
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
public const string DefaultScheme = "API Key";
public string AuthenticationType = DefaultScheme;
public string Scheme => DefaultScheme;
}
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private const string ProblemDetailsContentType = "application/problem+json";
public const string ApiKeyHeaderName = "X-Api-Key";
private readonly DTOSerializer _dtos;
private readonly AppSettings _settings;
private readonly SqlService _sql;
private readonly MetricsKeyCache _keyCache;
public ApiKeyAuthenticationHandler(
IOptionsMonitor<ApiKeyAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
MetricsKeyCache keyCache,
DTOSerializer dtos,
AppSettings settings,
SqlService db) : base(options, logger, encoder, clock)
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
_sql = db;
_dtos = dtos;
_keyCache = keyCache;
_settings = settings;
2020-05-09 22:16:16 +00:00
}
2021-10-23 16:51:17 +00:00
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
var metricsKey = Request.Headers[_settings.MetricsKeyHeader].FirstOrDefault();
// Never needed this, disabled for now
//await LogRequest(metricsKey);
if (metricsKey != default)
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
await _keyCache.AddKey(metricsKey);
if (await _sql.IsTarKey(metricsKey))
2020-06-14 13:13:29 +00:00
{
2021-10-23 16:51:17 +00:00
await _sql.IngestMetric(new Metric
2020-06-14 13:13:29 +00:00
{
2021-10-23 16:51:17 +00:00
Action = "TarKey",
Subject = "Auth",
MetricsKey = metricsKey,
Timestamp = DateTime.UtcNow
});
await Task.Delay(TimeSpan.FromSeconds(60));
throw new Exception("Error, lipsum timeout of the cross distant cloud.");
2020-06-14 13:13:29 +00:00
}
2021-10-23 16:51:17 +00:00
}
2020-06-14 13:13:29 +00:00
2021-10-23 16:51:17 +00:00
var authorKey = Request.Headers[ApiKeyHeaderName].FirstOrDefault();
2021-02-17 05:46:05 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey == null)
Request.Cookies.TryGetValue(ApiKeyHeaderName, out authorKey);
2021-02-17 05:46:05 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey == null && metricsKey == null) return AuthenticateResult.NoResult();
2020-05-09 22:16:16 +00:00
2020-06-16 22:21:01 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey != null)
{
var owner = await _sql.LoginByApiKey(authorKey);
if (owner == null)
return AuthenticateResult.Fail("Invalid author key");
2020-06-16 22:21:01 +00:00
2021-10-23 16:51:17 +00:00
var claims = new List<Claim> {new(ClaimTypes.Name, owner)};
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
claims.Add(new Claim(ClaimTypes.Role, "Author"));
claims.Add(new Claim(ClaimTypes.Role, "User"));
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
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);
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
return AuthenticateResult.Success(ticket);
}
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
if (!await _keyCache.IsValidKey(metricsKey))
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
return AuthenticateResult.Fail("Invalid Metrics Key");
2020-05-09 22:16:16 +00:00
}
{
2021-10-23 16:51:17 +00:00
var claims = new List<Claim> {new(ClaimTypes.Role, "User")};
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 AuthenticateResult.Success(ticket);
2020-05-09 22:16:16 +00:00
}
}
2021-10-23 16:51:17 +00:00
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
Response.StatusCode = 401;
Response.ContentType = ProblemDetailsContentType;
await Response.WriteAsync("Unauthorized");
}
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = 403;
Response.ContentType = ProblemDetailsContentType;
await Response.WriteAsync("forbidden");
2020-05-09 22:16:16 +00:00
}
}
2021-10-23 16:51:17 +00:00
public static class ApiKeyAuthorizationHandlerExtensions
{
public static AuthenticationBuilder AddApiKeySupport(this AuthenticationBuilder authenticationBuilder,
Action<ApiKeyAuthenticationOptions> options)
{
return authenticationBuilder.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(
ApiKeyAuthenticationOptions.DefaultScheme, options);
}
}