CustomAuthenticationHandler.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. {
  40. IgnoreLegacyAuth = true
  41. };
  42. try
  43. {
  44. var user = _authService.Authenticate(Request, authenticatedAttribute);
  45. if (user == null)
  46. {
  47. return Task.FromResult(AuthenticateResult.NoResult());
  48. // TODO return when legacy API is removed.
  49. // Don't spam the log with "Invalid User"
  50. // return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
  51. }
  52. var claims = new[]
  53. {
  54. new Claim(ClaimTypes.Name, user.Name),
  55. new Claim(
  56. ClaimTypes.Role,
  57. value: user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User)
  58. };
  59. var identity = new ClaimsIdentity(claims, Scheme.Name);
  60. var principal = new ClaimsPrincipal(identity);
  61. var ticket = new AuthenticationTicket(principal, Scheme.Name);
  62. return Task.FromResult(AuthenticateResult.Success(ticket));
  63. }
  64. catch (AuthenticationException ex)
  65. {
  66. return Task.FromResult(AuthenticateResult.Fail(ex));
  67. }
  68. catch (SecurityException ex)
  69. {
  70. return Task.FromResult(AuthenticateResult.Fail(ex));
  71. }
  72. }
  73. }
  74. }