AuthService.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Controller.Session;
  5. using ServiceStack;
  6. using ServiceStack.Auth;
  7. using ServiceStack.Web;
  8. using System;
  9. using System.Collections.Specialized;
  10. using System.Linq;
  11. namespace MediaBrowser.Server.Implementations.HttpServer.Security
  12. {
  13. public class AuthService : IAuthService
  14. {
  15. private readonly IServerConfigurationManager _config;
  16. public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config)
  17. {
  18. AuthorizationContext = authorizationContext;
  19. _config = config;
  20. SessionManager = sessionManager;
  21. UserManager = userManager;
  22. }
  23. public IUserManager UserManager { get; private set; }
  24. public ISessionManager SessionManager { get; private set; }
  25. public IAuthorizationContext AuthorizationContext { get; private set; }
  26. /// <summary>
  27. /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
  28. /// For example, if this attribute should only permit access
  29. /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
  30. /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
  31. /// </summary>
  32. public string Provider { get; set; }
  33. /// <summary>
  34. /// Redirect the client to a specific URL if authentication failed.
  35. /// If this property is null, simply `401 Unauthorized` is returned.
  36. /// </summary>
  37. public string HtmlRedirect { get; set; }
  38. public void Authenticate(IRequest req, IResponse res, object requestDto)
  39. {
  40. if (HostContext.HasValidAuthSecret(req))
  41. return;
  42. ExecuteBasic(req, res, requestDto); //first check if session is authenticated
  43. if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)
  44. ValidateUser(req);
  45. }
  46. private void ValidateUser(IRequest req)
  47. {
  48. //This code is executed before the service
  49. var auth = AuthorizationContext.GetAuthorizationInfo(req);
  50. if (!string.IsNullOrWhiteSpace(auth.Token) || _config.Configuration.EnableTokenAuthentication)
  51. {
  52. SessionManager.ValidateSecurityToken(auth.Token);
  53. }
  54. var user = string.IsNullOrWhiteSpace(auth.UserId)
  55. ? null
  56. : UserManager.GetUserById(new Guid(auth.UserId));
  57. if (user != null && user.Configuration.IsDisabled)
  58. {
  59. throw new UnauthorizedAccessException("User account has been disabled.");
  60. }
  61. if (!string.IsNullOrWhiteSpace(auth.DeviceId) &&
  62. !string.IsNullOrWhiteSpace(auth.Client) &&
  63. !string.IsNullOrWhiteSpace(auth.Device))
  64. {
  65. SessionManager.LogSessionActivity(auth.Client,
  66. auth.Version,
  67. auth.DeviceId,
  68. auth.Device,
  69. req.RemoteIp,
  70. user);
  71. }
  72. }
  73. private void ExecuteBasic(IRequest req, IResponse res, object requestDto)
  74. {
  75. if (AuthenticateService.AuthProviders == null)
  76. throw new InvalidOperationException(
  77. "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");
  78. var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
  79. this.Provider.IsNullOrEmpty()
  80. || x.Provider == this.Provider).ToList();
  81. if (matchingOAuthConfigs.Count == 0)
  82. {
  83. res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
  84. .Fmt(this.Provider ?? "any"));
  85. res.EndRequest();
  86. }
  87. matchingOAuthConfigs.OfType<IAuthWithRequest>()
  88. .Each(x => x.PreAuthenticate(req, res));
  89. var session = req.GetSession();
  90. if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
  91. {
  92. if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;
  93. AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
  94. }
  95. }
  96. protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
  97. {
  98. var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
  99. if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
  100. {
  101. DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
  102. return true;
  103. }
  104. return false;
  105. }
  106. public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
  107. {
  108. var url = req.ResolveAbsoluteUrl(redirectUrl);
  109. if (includeRedirectParam)
  110. {
  111. var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
  112. url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
  113. }
  114. res.RedirectToUrl(url);
  115. }
  116. private static string ToQueryString(INameValueCollection queryStringCollection)
  117. {
  118. return ToQueryString((NameValueCollection)queryStringCollection.Original);
  119. }
  120. private static string ToQueryString(NameValueCollection queryStringCollection)
  121. {
  122. if (queryStringCollection == null || queryStringCollection.Count == 0)
  123. return String.Empty;
  124. return "?" + queryStringCollection.ToFormUrlEncoded();
  125. }
  126. }
  127. }