AuthorizationContext.cs 9.7 KB

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