CustomAuthenticationHandler.cs 2.8 KB

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