//
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see https://www.gnu.org/licenses/.
//
using Microsoft.Extensions.Options;
namespace slskd.Authentication
{
using System;
using System.Security.Principal;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
///
/// API key authentication.
///
public static class ApiKeyAuthentication
{
///
/// Gets the API key authentication scheme name.
///
public static string AuthenticationScheme { get; } = "ApiKey";
}
///
/// Handles API key authentication.
///
public class ApiKeyAuthenticationHandler : AuthenticationHandler
{
///
/// Initializes a new instance of the class.
///
/// An options monitor.
/// The security service.
/// A logger factory.
/// A url encoder.
/// A system clock interface.
public ApiKeyAuthenticationHandler(
IOptionsMonitor apiKeyOptionsMonitor,
ISecurityService securityService,
ILoggerFactory logger,
UrlEncoder urlEncoder,
ISystemClock systemClock)
: base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock)
{
Security = securityService;
}
private ISecurityService Security { get; }
///
/// Authenticates via API key.
///
/// A successful authentication result containing a ticket for the API key.
protected override async Task HandleAuthenticateAsync()
{
await Task.Yield();
if (!Request.Headers.TryGetValue("X-API-Key", out var headerKeyValue))
{
return AuthenticateResult.NoResult();
}
try
{
var key = Security.AuthenticateWithApiKey(headerKeyValue, Request.HttpContext.Connection.RemoteIpAddress);
var identity = new GenericIdentity(key.Name);
var principal = new GenericPrincipal(identity, new[] { key.Role.ToString() });
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), ApiKeyAuthentication.AuthenticationScheme);
return AuthenticateResult.Success(ticket);
}
catch (Exception ex)
{
return AuthenticateResult.Fail(ex);
}
}
}
///
/// API key authentication options.
///
#pragma warning disable S2094 // Classes should not be empty
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
#pragma warning restore S2094 // Classes should not be empty
{
}
}