AuthorizationContext.cs 7.9 KB

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