AuthService.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Connect;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Security;
  8. using MediaBrowser.Controller.Session;
  9. using System;
  10. using System.Collections.Generic;
  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, IAuthorizationContext authorizationContext, IServerConfigurationManager config, IConnectManager connectManager, ISessionManager sessionManager, IDeviceManager deviceManager)
  18. {
  19. AuthorizationContext = authorizationContext;
  20. _config = config;
  21. DeviceManager = deviceManager;
  22. SessionManager = sessionManager;
  23. ConnectManager = connectManager;
  24. UserManager = userManager;
  25. }
  26. public IUserManager UserManager { get; private set; }
  27. public IAuthorizationContext AuthorizationContext { get; private set; }
  28. public IConnectManager ConnectManager { get; private set; }
  29. public ISessionManager SessionManager { get; private set; }
  30. public IDeviceManager DeviceManager { get; private set; }
  31. /// <summary>
  32. /// Redirect the client to a specific URL if authentication failed.
  33. /// If this property is null, simply `401 Unauthorized` is returned.
  34. /// </summary>
  35. public string HtmlRedirect { get; set; }
  36. public void Authenticate(IServiceRequest request,
  37. IAuthenticationAttributes authAttribtues)
  38. {
  39. ValidateUser(request, authAttribtues);
  40. }
  41. private void ValidateUser(IServiceRequest request,
  42. IAuthenticationAttributes authAttribtues)
  43. {
  44. // This code is executed before the service
  45. var auth = AuthorizationContext.GetAuthorizationInfo(request);
  46. if (!IsExemptFromAuthenticationToken(auth, authAttribtues))
  47. {
  48. var valid = IsValidConnectKey(auth.Token);
  49. if (!valid)
  50. {
  51. ValidateSecurityToken(request, auth.Token);
  52. }
  53. }
  54. var user = string.IsNullOrWhiteSpace(auth.UserId)
  55. ? null
  56. : UserManager.GetUserById(auth.UserId);
  57. if (user == null & !string.IsNullOrWhiteSpace(auth.UserId))
  58. {
  59. throw new SecurityException("User with Id " + auth.UserId + " not found");
  60. }
  61. if (user != null)
  62. {
  63. ValidateUserAccess(user, request, authAttribtues, auth);
  64. }
  65. var info = GetTokenInfo(request);
  66. if (!IsExemptFromRoles(auth, authAttribtues, info))
  67. {
  68. var roles = authAttribtues.GetRoles().ToList();
  69. ValidateRoles(roles, user);
  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. request.RemoteIp,
  80. user);
  81. }
  82. }
  83. private void ValidateUserAccess(User user, IServiceRequest request,
  84. IAuthenticationAttributes authAttribtues,
  85. AuthorizationInfo auth)
  86. {
  87. if (user.Policy.IsDisabled)
  88. {
  89. throw new SecurityException("User account has been disabled.")
  90. {
  91. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  92. };
  93. }
  94. if (!user.Policy.IsAdministrator &&
  95. !authAttribtues.EscapeParentalControl &&
  96. !user.IsParentalScheduleAllowed())
  97. {
  98. request.AddResponseHeader("X-Application-Error-Code", "ParentalControl");
  99. throw new SecurityException("This user account is not allowed access at this time.")
  100. {
  101. SecurityExceptionType = SecurityExceptionType.ParentalControl
  102. };
  103. }
  104. if (!string.IsNullOrWhiteSpace(auth.DeviceId))
  105. {
  106. if (!DeviceManager.CanAccessDevice(user.Id.ToString("N"), auth.DeviceId))
  107. {
  108. throw new SecurityException("User is not allowed access from this device.")
  109. {
  110. SecurityExceptionType = SecurityExceptionType.ParentalControl
  111. };
  112. }
  113. }
  114. }
  115. private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues)
  116. {
  117. if (!_config.Configuration.IsStartupWizardCompleted &&
  118. authAttribtues.AllowBeforeStartupWizard)
  119. {
  120. return true;
  121. }
  122. return _config.Configuration.InsecureApps8.Contains(auth.Client ?? string.Empty,
  123. StringComparer.OrdinalIgnoreCase);
  124. }
  125. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, AuthenticationInfo tokenInfo)
  126. {
  127. if (!_config.Configuration.IsStartupWizardCompleted &&
  128. authAttribtues.AllowBeforeStartupWizard)
  129. {
  130. return true;
  131. }
  132. if (string.IsNullOrWhiteSpace(auth.Token))
  133. {
  134. return true;
  135. }
  136. if (tokenInfo != null && string.IsNullOrWhiteSpace(tokenInfo.UserId))
  137. {
  138. return true;
  139. }
  140. return false;
  141. }
  142. private void ValidateRoles(List<string> roles, User user)
  143. {
  144. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  145. {
  146. if (user == null || !user.Policy.IsAdministrator)
  147. {
  148. throw new SecurityException("User does not have admin access.")
  149. {
  150. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  151. };
  152. }
  153. }
  154. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  155. {
  156. if (user == null || !user.Policy.EnableContentDeletion)
  157. {
  158. throw new SecurityException("User does not have delete access.")
  159. {
  160. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  161. };
  162. }
  163. }
  164. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  165. {
  166. if (user == null || !user.Policy.EnableContentDownloading)
  167. {
  168. throw new SecurityException("User does not have download access.")
  169. {
  170. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  171. };
  172. }
  173. }
  174. }
  175. private AuthenticationInfo GetTokenInfo(IServiceRequest request)
  176. {
  177. object info;
  178. request.Items.TryGetValue("OriginalAuthenticationInfo", out info);
  179. return info as AuthenticationInfo;
  180. }
  181. private bool IsValidConnectKey(string token)
  182. {
  183. if (string.IsNullOrEmpty(token))
  184. {
  185. return false;
  186. }
  187. return ConnectManager.IsAuthorizationTokenValid(token);
  188. }
  189. private void ValidateSecurityToken(IServiceRequest request, string token)
  190. {
  191. if (string.IsNullOrWhiteSpace(token))
  192. {
  193. throw new SecurityException("Access token is invalid or expired.");
  194. }
  195. var info = GetTokenInfo(request);
  196. if (info == null)
  197. {
  198. throw new SecurityException("Access token is invalid or expired.");
  199. }
  200. if (!info.IsActive)
  201. {
  202. throw new SecurityException("Access token has expired.");
  203. }
  204. //if (!string.IsNullOrWhiteSpace(info.UserId))
  205. //{
  206. // var user = _userManager.GetUserById(info.UserId);
  207. // if (user == null || user.Configuration.IsDisabled)
  208. // {
  209. // throw new SecurityException("User account has been disabled.");
  210. // }
  211. //}
  212. }
  213. }
  214. }