2019-11-23 15:31:02 +00:00
|
|
|
using System.Security.Claims;
|
|
|
|
using System.Text.Encodings.Web;
|
|
|
|
using System.Threading.Tasks;
|
2019-11-24 17:25:43 +00:00
|
|
|
using Jellyfin.Api.Constants;
|
2019-11-23 15:31:02 +00:00
|
|
|
using MediaBrowser.Controller.Net;
|
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
|
|
namespace Jellyfin.Api.Auth
|
|
|
|
{
|
2019-11-23 19:31:17 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Custom authentication handler wrapping the legacy authentication.
|
|
|
|
/// </summary>
|
2019-11-23 15:31:02 +00:00
|
|
|
public class CustomAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
|
|
|
{
|
|
|
|
private readonly IAuthService _authService;
|
|
|
|
|
2019-11-23 19:31:17 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Initializes a new instance of the <see cref="CustomAuthenticationHandler" /> class.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="authService">The jellyfin authentication service.</param>
|
|
|
|
/// <param name="options">Options monitor.</param>
|
|
|
|
/// <param name="logger">The logger.</param>
|
|
|
|
/// <param name="encoder">The url encoder.</param>
|
|
|
|
/// <param name="clock">The system clock.</param>
|
2019-11-23 15:31:02 +00:00
|
|
|
public CustomAuthenticationHandler(
|
|
|
|
IAuthService authService,
|
|
|
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
|
|
|
ILoggerFactory logger,
|
|
|
|
UrlEncoder encoder,
|
|
|
|
ISystemClock clock) : base(options, logger, encoder, clock)
|
|
|
|
{
|
|
|
|
_authService = authService;
|
|
|
|
}
|
|
|
|
|
2019-11-23 19:31:17 +00:00
|
|
|
/// <inheritdoc />
|
2019-11-23 15:31:02 +00:00
|
|
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
|
|
{
|
|
|
|
var authenticatedAttribute = new AuthenticatedAttribute();
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var user = _authService.Authenticate(Request, authenticatedAttribute);
|
|
|
|
if (user == null)
|
|
|
|
{
|
|
|
|
return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
|
|
|
|
}
|
|
|
|
|
|
|
|
var claims = new[]
|
|
|
|
{
|
|
|
|
new Claim(ClaimTypes.Name, user.Name),
|
2019-11-23 19:31:17 +00:00
|
|
|
new Claim(
|
|
|
|
ClaimTypes.Role,
|
2019-11-24 17:25:43 +00:00
|
|
|
value: user.Policy.IsAdministrator ? UserRole.Administrator : UserRole.User)
|
2019-11-23 15:31:02 +00:00
|
|
|
};
|
|
|
|
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
|
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
|
|
|
|
|
|
|
return Task.FromResult(AuthenticateResult.Success(ticket));
|
|
|
|
}
|
|
|
|
catch (SecurityException ex)
|
|
|
|
{
|
|
|
|
return Task.FromResult(AuthenticateResult.Fail(ex));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|