AuthorizationContext.cs 9.7 KB

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