AuthorizationContext.cs 8.0 KB

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