AuthService.cs 6.4 KB

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