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