AuthorizationContext.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using MediaBrowser.Controller.Connect;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Controller.Security;
  4. using System;
  5. using System.Collections.Generic;
  6. using MediaBrowser.Model.Services;
  7. using System.Linq;
  8. using System.Threading;
  9. using MediaBrowser.Controller.Library;
  10. namespace Emby.Server.Implementations.HttpServer.Security
  11. {
  12. public class AuthorizationContext : IAuthorizationContext
  13. {
  14. private readonly IAuthenticationRepository _authRepo;
  15. private readonly IConnectManager _connectManager;
  16. private readonly IUserManager _userManager;
  17. public AuthorizationContext(IAuthenticationRepository authRepo, IConnectManager connectManager, IUserManager userManager)
  18. {
  19. _authRepo = authRepo;
  20. _connectManager = connectManager;
  21. _userManager = userManager;
  22. }
  23. public AuthorizationInfo GetAuthorizationInfo(object requestContext)
  24. {
  25. return GetAuthorizationInfo((IRequest)requestContext);
  26. }
  27. public AuthorizationInfo GetAuthorizationInfo(IRequest requestContext)
  28. {
  29. object cached;
  30. if (requestContext.Items.TryGetValue("AuthorizationInfo", out cached))
  31. {
  32. return (AuthorizationInfo)cached;
  33. }
  34. return GetAuthorization(requestContext);
  35. }
  36. /// <summary>
  37. /// Gets the authorization.
  38. /// </summary>
  39. /// <param name="httpReq">The HTTP req.</param>
  40. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  41. private AuthorizationInfo GetAuthorization(IRequest httpReq)
  42. {
  43. var auth = GetAuthorizationDictionary(httpReq);
  44. string deviceId = null;
  45. string device = null;
  46. string client = null;
  47. string version = null;
  48. string token = null;
  49. if (auth != null)
  50. {
  51. auth.TryGetValue("DeviceId", out deviceId);
  52. auth.TryGetValue("Device", out device);
  53. auth.TryGetValue("Client", out client);
  54. auth.TryGetValue("Version", out version);
  55. auth.TryGetValue("Token", out token);
  56. }
  57. if (string.IsNullOrEmpty(token))
  58. {
  59. token = httpReq.Headers["X-Emby-Token"];
  60. }
  61. if (string.IsNullOrEmpty(token))
  62. {
  63. token = httpReq.Headers["X-MediaBrowser-Token"];
  64. }
  65. if (string.IsNullOrEmpty(token))
  66. {
  67. token = httpReq.QueryString["api_key"];
  68. }
  69. var info = new AuthorizationInfo
  70. {
  71. Client = client,
  72. Device = device,
  73. DeviceId = deviceId,
  74. Version = version,
  75. Token = token
  76. };
  77. if (!string.IsNullOrWhiteSpace(token))
  78. {
  79. var result = _authRepo.Get(new AuthenticationInfoQuery
  80. {
  81. AccessToken = token
  82. });
  83. var tokenInfo = result.Items.Length > 0 ? result.Items[0] : null;
  84. if (tokenInfo != null)
  85. {
  86. var updateToken = false;
  87. // TODO: Remove these checks for IsNullOrWhiteSpace
  88. if (string.IsNullOrWhiteSpace(info.Client))
  89. {
  90. info.Client = tokenInfo.AppName;
  91. }
  92. if (string.IsNullOrWhiteSpace(info.DeviceId))
  93. {
  94. info.DeviceId = tokenInfo.DeviceId;
  95. }
  96. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  97. var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
  98. if (string.IsNullOrWhiteSpace(info.Device))
  99. {
  100. info.Device = tokenInfo.DeviceName;
  101. }
  102. else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
  103. {
  104. if (allowTokenInfoUpdate)
  105. {
  106. updateToken = true;
  107. tokenInfo.DeviceName = info.Device;
  108. }
  109. }
  110. if (string.IsNullOrWhiteSpace(info.Version))
  111. {
  112. info.Version = tokenInfo.AppVersion;
  113. }
  114. else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
  115. {
  116. if (allowTokenInfoUpdate)
  117. {
  118. updateToken = true;
  119. tokenInfo.AppVersion = info.Version;
  120. }
  121. }
  122. if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
  123. {
  124. tokenInfo.DateLastActivity = DateTime.UtcNow;
  125. updateToken = true;
  126. }
  127. if (!tokenInfo.UserId.Equals(Guid.Empty))
  128. {
  129. info.User = _userManager.GetUserById(tokenInfo.UserId);
  130. if (info.User != null && !string.Equals(info.User.Name, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
  131. {
  132. tokenInfo.UserName = info.User.Name;
  133. updateToken = true;
  134. }
  135. }
  136. if (updateToken)
  137. {
  138. _authRepo.Update(tokenInfo);
  139. }
  140. }
  141. httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
  142. }
  143. httpReq.Items["AuthorizationInfo"] = info;
  144. return info;
  145. }
  146. /// <summary>
  147. /// Gets the auth.
  148. /// </summary>
  149. /// <param name="httpReq">The HTTP req.</param>
  150. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  151. private Dictionary<string, string> GetAuthorizationDictionary(IRequest httpReq)
  152. {
  153. var auth = httpReq.Headers["X-Emby-Authorization"];
  154. if (string.IsNullOrEmpty(auth))
  155. {
  156. auth = httpReq.Headers["Authorization"];
  157. }
  158. return GetAuthorization(auth);
  159. }
  160. /// <summary>
  161. /// Gets the authorization.
  162. /// </summary>
  163. /// <param name="authorizationHeader">The authorization header.</param>
  164. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  165. private Dictionary<string, string> GetAuthorization(string authorizationHeader)
  166. {
  167. if (authorizationHeader == null) return null;
  168. var parts = authorizationHeader.Split(new[] { ' ' }, 2);
  169. // There should be at least to parts
  170. if (parts.Length != 2) return null;
  171. var acceptedNames = new[] { "MediaBrowser", "Emby" };
  172. // It has to be a digest request
  173. if (!acceptedNames.Contains(parts[0] ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  174. {
  175. return null;
  176. }
  177. // Remove uptil the first space
  178. authorizationHeader = parts[1];
  179. parts = authorizationHeader.Split(',');
  180. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  181. foreach (var item in parts)
  182. {
  183. var param = item.Trim().Split(new[] { '=' }, 2);
  184. if (param.Length == 2)
  185. {
  186. var value = NormalizeValue(param[1].Trim(new[] { '"' }));
  187. result.Add(param[0], value);
  188. }
  189. }
  190. return result;
  191. }
  192. private string NormalizeValue(string value)
  193. {
  194. if (string.IsNullOrEmpty(value))
  195. {
  196. return value;
  197. }
  198. return System.Net.WebUtility.HtmlEncode(value);
  199. }
  200. }
  201. }