AuthorizationContext.cs 10 KB

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