CustomAuthenticationHandler.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Security.Claims;
  2. using System.Text.Encodings.Web;
  3. using System.Threading.Tasks;
  4. using Jellyfin.Api.Constants;
  5. using MediaBrowser.Controller.Net;
  6. using Microsoft.AspNetCore.Authentication;
  7. using Microsoft.Extensions.Logging;
  8. using Microsoft.Extensions.Options;
  9. namespace Jellyfin.Api.Auth
  10. {
  11. /// <summary>
  12. /// Custom authentication handler wrapping the legacy authentication.
  13. /// </summary>
  14. public class CustomAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
  15. {
  16. private readonly IAuthService _authService;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="CustomAuthenticationHandler" /> class.
  19. /// </summary>
  20. /// <param name="authService">The jellyfin authentication service.</param>
  21. /// <param name="options">Options monitor.</param>
  22. /// <param name="logger">The logger.</param>
  23. /// <param name="encoder">The url encoder.</param>
  24. /// <param name="clock">The system clock.</param>
  25. public CustomAuthenticationHandler(
  26. IAuthService authService,
  27. IOptionsMonitor<AuthenticationSchemeOptions> options,
  28. ILoggerFactory logger,
  29. UrlEncoder encoder,
  30. ISystemClock clock) : base(options, logger, encoder, clock)
  31. {
  32. _authService = authService;
  33. }
  34. /// <inheritdoc />
  35. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  36. {
  37. var authenticatedAttribute = new AuthenticatedAttribute
  38. {
  39. IgnoreLegacyAuth = true
  40. };
  41. try
  42. {
  43. var user = _authService.Authenticate(Request, authenticatedAttribute);
  44. if (user == null)
  45. {
  46. return Task.FromResult(AuthenticateResult.NoResult());
  47. // TODO return when legacy API is removed.
  48. // Don't spam the log with "Invalid User"
  49. // return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
  50. }
  51. var claims = new[]
  52. {
  53. new Claim(ClaimTypes.Name, user.Name),
  54. new Claim(
  55. ClaimTypes.Role,
  56. value: user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User)
  57. };
  58. var identity = new ClaimsIdentity(claims, Scheme.Name);
  59. var principal = new ClaimsPrincipal(identity);
  60. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  61. return Task.FromResult(AuthenticateResult.Success(ticket));
  62. }
  63. catch (SecurityException ex)
  64. {
  65. return Task.FromResult(AuthenticateResult.Fail(ex));
  66. }
  67. }
  68. }
  69. }