AuthService.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. using MediaBrowser.Common.Net;
  13. namespace Emby.Server.Implementations.HttpServer.Security
  14. {
  15. public class AuthService : IAuthService
  16. {
  17. private readonly IServerConfigurationManager _config;
  18. public AuthService(IUserManager userManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, IConnectManager connectManager, ISessionManager sessionManager, INetworkManager networkManager)
  19. {
  20. AuthorizationContext = authorizationContext;
  21. _config = config;
  22. SessionManager = sessionManager;
  23. ConnectManager = connectManager;
  24. UserManager = userManager;
  25. NetworkManager = networkManager;
  26. }
  27. public IUserManager UserManager { get; private set; }
  28. public IAuthorizationContext AuthorizationContext { get; private set; }
  29. public IConnectManager ConnectManager { get; private set; }
  30. public ISessionManager SessionManager { get; private set; }
  31. public INetworkManager NetworkManager { get; private set; }
  32. /// <summary>
  33. /// Redirect the client to a specific URL if authentication failed.
  34. /// If this property is null, simply `401 Unauthorized` is returned.
  35. /// </summary>
  36. public string HtmlRedirect { get; set; }
  37. public void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues)
  38. {
  39. ValidateUser(request, authAttribtues);
  40. }
  41. private void ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
  42. {
  43. // This code is executed before the service
  44. var auth = AuthorizationContext.GetAuthorizationInfo(request);
  45. if (!IsExemptFromAuthenticationToken(auth, authAttribtues, request))
  46. {
  47. var valid = IsValidConnectKey(auth.Token);
  48. if (!valid)
  49. {
  50. ValidateSecurityToken(request, auth.Token);
  51. }
  52. }
  53. if (authAttribtues.AllowLocalOnly && !request.IsLocal)
  54. {
  55. throw new SecurityException("Operation not found.");
  56. }
  57. var user = auth.User;
  58. if (user == null & !auth.UserId.Equals(Guid.Empty))
  59. {
  60. throw new SecurityException("User with Id " + auth.UserId + " not found");
  61. }
  62. if (user != null)
  63. {
  64. ValidateUserAccess(user, request, authAttribtues, auth);
  65. }
  66. var info = GetTokenInfo(request);
  67. if (!IsExemptFromRoles(auth, authAttribtues, request, info))
  68. {
  69. var roles = authAttribtues.GetRoles();
  70. ValidateRoles(roles, user);
  71. }
  72. if (!string.IsNullOrEmpty(auth.DeviceId) &&
  73. !string.IsNullOrEmpty(auth.Client) &&
  74. !string.IsNullOrEmpty(auth.Device))
  75. {
  76. SessionManager.LogSessionActivity(auth.Client,
  77. auth.Version,
  78. auth.DeviceId,
  79. auth.Device,
  80. request.RemoteIp,
  81. user);
  82. }
  83. }
  84. private void ValidateUserAccess(User user, IRequest request,
  85. IAuthenticationAttributes authAttribtues,
  86. AuthorizationInfo auth)
  87. {
  88. if (user.Policy.IsDisabled)
  89. {
  90. throw new SecurityException("User account has been disabled.")
  91. {
  92. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  93. };
  94. }
  95. if (!user.Policy.EnableRemoteAccess && !NetworkManager.IsInLocalNetwork(request.RemoteIp))
  96. {
  97. throw new SecurityException("User account has been disabled.")
  98. {
  99. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  100. };
  101. }
  102. if (!user.Policy.IsAdministrator &&
  103. !authAttribtues.EscapeParentalControl &&
  104. !user.IsParentalScheduleAllowed())
  105. {
  106. request.Response.AddHeader("X-Application-Error-Code", "ParentalControl");
  107. throw new SecurityException("This user account is not allowed access at this time.")
  108. {
  109. SecurityExceptionType = SecurityExceptionType.ParentalControl
  110. };
  111. }
  112. }
  113. private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request)
  114. {
  115. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  116. {
  117. return true;
  118. }
  119. if (authAttribtues.AllowLocal && request.IsLocal)
  120. {
  121. return true;
  122. }
  123. if (authAttribtues.AllowLocalOnly && request.IsLocal)
  124. {
  125. return true;
  126. }
  127. return false;
  128. }
  129. private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo)
  130. {
  131. if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard)
  132. {
  133. return true;
  134. }
  135. if (authAttribtues.AllowLocal && request.IsLocal)
  136. {
  137. return true;
  138. }
  139. if (authAttribtues.AllowLocalOnly && request.IsLocal)
  140. {
  141. return true;
  142. }
  143. if (string.IsNullOrEmpty(auth.Token))
  144. {
  145. return true;
  146. }
  147. if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty))
  148. {
  149. return true;
  150. }
  151. return false;
  152. }
  153. private void ValidateRoles(string[] roles, User user)
  154. {
  155. if (roles.Contains("admin", StringComparer.OrdinalIgnoreCase))
  156. {
  157. if (user == null || !user.Policy.IsAdministrator)
  158. {
  159. throw new SecurityException("User does not have admin access.")
  160. {
  161. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  162. };
  163. }
  164. }
  165. if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
  166. {
  167. if (user == null || !user.Policy.EnableContentDeletion)
  168. {
  169. throw new SecurityException("User does not have delete access.")
  170. {
  171. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  172. };
  173. }
  174. }
  175. if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
  176. {
  177. if (user == null || !user.Policy.EnableContentDownloading)
  178. {
  179. throw new SecurityException("User does not have download access.")
  180. {
  181. SecurityExceptionType = SecurityExceptionType.Unauthenticated
  182. };
  183. }
  184. }
  185. }
  186. private AuthenticationInfo GetTokenInfo(IRequest request)
  187. {
  188. object info;
  189. request.Items.TryGetValue("OriginalAuthenticationInfo", out info);
  190. return info as AuthenticationInfo;
  191. }
  192. private bool IsValidConnectKey(string token)
  193. {
  194. if (string.IsNullOrEmpty(token))
  195. {
  196. return false;
  197. }
  198. return ConnectManager.IsAuthorizationTokenValid(token);
  199. }
  200. private void ValidateSecurityToken(IRequest request, string token)
  201. {
  202. if (string.IsNullOrEmpty(token))
  203. {
  204. throw new SecurityException("Access token is required.");
  205. }
  206. var info = GetTokenInfo(request);
  207. if (info == null)
  208. {
  209. throw new SecurityException("Access token is invalid or expired.");
  210. }
  211. //if (!string.IsNullOrEmpty(info.UserId))
  212. //{
  213. // var user = _userManager.GetUserById(info.UserId);
  214. // if (user == null || user.Configuration.IsDisabled)
  215. // {
  216. // throw new SecurityException("User account has been disabled.");
  217. // }
  218. //}
  219. }
  220. }
  221. }