AuthService.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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.Linq;
  11. using MediaBrowser.Model.Services;
  12. namespace Emby.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(IRequest request,
  37. IAuthenticationAttributes authAttribtues)
  38. {
  39. ValidateUser(request, authAttribtues);
  40. }
  41. private void ValidateUser(IRequest request,
  42. IAuthenticationAttributes authAttribtues)
  43. {
  44. // This code is executed before the service
  45. var auth = AuthorizationContext.GetAuthorizationInfo(request);
  46. if (!IsExemptFromAuthenticationToken(auth, authAttribtues, request))
  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, request, info))
  67. {
  68. var roles = authAttribtues.GetRoles();
  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, IRequest 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.Response.AddHeader("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, IRequest request)
  116. {
  117. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  118. {
  119. return true;
  120. }
  121. if (authAttribtues.AllowLocal && request.IsLocal)
  122. {
  123. return true;
  124. }
  125. return false;
  126. }
  127. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
  128. {
  129. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  130. {
  131. return true;
  132. }
  133. if (authAttribtues.AllowLocal && request.IsLocal)
  134. {
  135. return true;
  136. }
  137. if (string.IsNullOrWhiteSpace(auth.Token))
  138. {
  139. return true;
  140. }
  141. if (tokenInfo != null && string.IsNullOrWhiteSpace(tokenInfo.UserId))
  142. {
  143. return true;
  144. }
  145. return false;
  146. }
  147. private void ValidateRoles(string[] roles, User user)
  148. {
  149. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  150. {
  151. if (user == null || !user.Policy.IsAdministrator)
  152. {
  153. throw new SecurityException("User does not have admin access.")
  154. {
  155. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  156. };
  157. }
  158. }
  159. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  160. {
  161. if (user == null || !user.Policy.EnableContentDeletion)
  162. {
  163. throw new SecurityException("User does not have delete access.")
  164. {
  165. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  166. };
  167. }
  168. }
  169. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  170. {
  171. if (user == null || !user.Policy.EnableContentDownloading)
  172. {
  173. throw new SecurityException("User does not have download access.")
  174. {
  175. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  176. };
  177. }
  178. }
  179. }
  180. private AuthenticationInfo GetTokenInfo(IRequest request)
  181. {
  182. object info;
  183. request.Items.TryGetValue("OriginalAuthenticationInfo", out info);
  184. return info as AuthenticationInfo;
  185. }
  186. private bool IsValidConnectKey(string token)
  187. {
  188. if (string.IsNullOrEmpty(token))
  189. {
  190. return false;
  191. }
  192. return ConnectManager.IsAuthorizationTokenValid(token);
  193. }
  194. private void ValidateSecurityToken(IRequest request, string token)
  195. {
  196. if (string.IsNullOrWhiteSpace(token))
  197. {
  198. throw new SecurityException("Access token is required.");
  199. }
  200. var info = GetTokenInfo(request);
  201. if (info == null)
  202. {
  203. throw new SecurityException("Access token is invalid or expired.");
  204. }
  205. if (!info.IsActive)
  206. {
  207. throw new SecurityException("Access token has expired.");
  208. }
  209. //if (!string.IsNullOrWhiteSpace(info.UserId))
  210. //{
  211. // var user = _userManager.GetUserById(info.UserId);
  212. // if (user == null || user.Configuration.IsDisabled)
  213. // {
  214. // throw new SecurityException("User account has been disabled.");
  215. // }
  216. //}
  217. }
  218. }
  219. }