AuthorizationContext.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. authInfo.IsApiKey = true;
  159. }
  160. else
  161. {
  162. authInfo.IsApiKey = false;
  163. }
  164. if (updateToken)
  165. {
  166. _authRepo.Update(originalAuthenticationInfo);
  167. }
  168. }
  169. return (authInfo, originalAuthenticationInfo);
  170. }
  171. /// <summary>
  172. /// Gets the auth.
  173. /// </summary>
  174. /// <param name="httpReq">The HTTP req.</param>
  175. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  176. private Dictionary<string, string> GetAuthorizationDictionary(HttpContext httpReq)
  177. {
  178. var auth = httpReq.Request.Headers["X-Emby-Authorization"];
  179. if (string.IsNullOrEmpty(auth))
  180. {
  181. auth = httpReq.Request.Headers[HeaderNames.Authorization];
  182. }
  183. return GetAuthorization(auth);
  184. }
  185. /// <summary>
  186. /// Gets the auth.
  187. /// </summary>
  188. /// <param name="httpReq">The HTTP req.</param>
  189. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  190. private Dictionary<string, string> GetAuthorizationDictionary(HttpRequest httpReq)
  191. {
  192. var auth = httpReq.Headers["X-Emby-Authorization"];
  193. if (string.IsNullOrEmpty(auth))
  194. {
  195. auth = httpReq.Headers[HeaderNames.Authorization];
  196. }
  197. return GetAuthorization(auth);
  198. }
  199. /// <summary>
  200. /// Gets the authorization.
  201. /// </summary>
  202. /// <param name="authorizationHeader">The authorization header.</param>
  203. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  204. private Dictionary<string, string> GetAuthorization(string authorizationHeader)
  205. {
  206. if (authorizationHeader == null)
  207. {
  208. return null;
  209. }
  210. var parts = authorizationHeader.Split(new[] { ' ' }, 2);
  211. // There should be at least to parts
  212. if (parts.Length != 2)
  213. {
  214. return null;
  215. }
  216. var acceptedNames = new[] { "MediaBrowser", "Emby" };
  217. // It has to be a digest request
  218. if (!acceptedNames.Contains(parts[0], StringComparer.OrdinalIgnoreCase))
  219. {
  220. return null;
  221. }
  222. // Remove uptil the first space
  223. authorizationHeader = parts[1];
  224. parts = authorizationHeader.Split(',');
  225. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  226. foreach (var item in parts)
  227. {
  228. var param = item.Trim().Split(new[] { '=' }, 2);
  229. if (param.Length == 2)
  230. {
  231. var value = NormalizeValue(param[1].Trim(new[] { '"' }));
  232. result[param[0]] = value;
  233. }
  234. }
  235. return result;
  236. }
  237. private static string NormalizeValue(string value)
  238. {
  239. return string.IsNullOrEmpty(value) ? value : WebUtility.HtmlEncode(value);
  240. }
  241. }
  242. }