CustomAuthenticationHandler.cs 2.7 KB

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