CustomAuthenticationHandler.cs 2.7 KB

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