CustomAuthenticationHandler.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. try
  39. {
  40. var user = _authService.Authenticate(Request, authenticatedAttribute);
  41. if (user == null)
  42. {
  43. return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
  44. }
  45. var claims = new[]
  46. {
  47. new Claim(ClaimTypes.Name, user.Name),
  48. new Claim(
  49. ClaimTypes.Role,
  50. value: user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User)
  51. };
  52. var identity = new ClaimsIdentity(claims, Scheme.Name);
  53. var principal = new ClaimsPrincipal(identity);
  54. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  55. return Task.FromResult(AuthenticateResult.Success(ticket));
  56. }
  57. catch (SecurityException ex)
  58. {
  59. return Task.FromResult(AuthenticateResult.Fail(ex));
  60. }
  61. }
  62. }
  63. }