AuthorizationContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Data.Queries;
  7. using Jellyfin.Extensions;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Controller.Devices;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Net;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.EntityFrameworkCore;
  14. using Microsoft.Net.Http.Headers;
  15. namespace Jellyfin.Server.Implementations.Security
  16. {
  17. public class AuthorizationContext : IAuthorizationContext
  18. {
  19. private readonly IDbContextFactory<JellyfinDbContext> _jellyfinDbProvider;
  20. private readonly IUserManager _userManager;
  21. private readonly IDeviceManager _deviceManager;
  22. private readonly IServerApplicationHost _serverApplicationHost;
  23. public AuthorizationContext(
  24. IDbContextFactory<JellyfinDbContext> jellyfinDb,
  25. IUserManager userManager,
  26. IDeviceManager deviceManager,
  27. IServerApplicationHost serverApplicationHost)
  28. {
  29. _jellyfinDbProvider = jellyfinDb;
  30. _userManager = userManager;
  31. _deviceManager = deviceManager;
  32. _serverApplicationHost = serverApplicationHost;
  33. }
  34. public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
  35. {
  36. if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached is not null)
  37. {
  38. return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
  39. }
  40. return GetAuthorization(requestContext);
  41. }
  42. public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
  43. {
  44. var auth = GetAuthorizationDictionary(requestContext);
  45. var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
  46. return authInfo;
  47. }
  48. /// <summary>
  49. /// Gets the authorization.
  50. /// </summary>
  51. /// <param name="httpContext">The HTTP context.</param>
  52. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  53. private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpContext)
  54. {
  55. var authInfo = await GetAuthorizationInfo(httpContext.Request).ConfigureAwait(false);
  56. httpContext.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  57. return authInfo;
  58. }
  59. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  60. Dictionary<string, string>? auth,
  61. IHeaderDictionary headers,
  62. IQueryCollection queryString)
  63. {
  64. string? deviceId = null;
  65. string? deviceName = null;
  66. string? client = null;
  67. string? version = null;
  68. string? token = null;
  69. if (auth is not null)
  70. {
  71. auth.TryGetValue("DeviceId", out deviceId);
  72. auth.TryGetValue("Device", out deviceName);
  73. auth.TryGetValue("Client", out client);
  74. auth.TryGetValue("Version", out version);
  75. auth.TryGetValue("Token", out token);
  76. }
  77. if (string.IsNullOrEmpty(token))
  78. {
  79. token = headers["X-Emby-Token"];
  80. }
  81. if (string.IsNullOrEmpty(token))
  82. {
  83. token = headers["X-MediaBrowser-Token"];
  84. }
  85. if (string.IsNullOrEmpty(token))
  86. {
  87. token = queryString["ApiKey"];
  88. }
  89. // TODO deprecate this query parameter.
  90. if (string.IsNullOrEmpty(token))
  91. {
  92. token = queryString["api_key"];
  93. }
  94. var authInfo = new AuthorizationInfo
  95. {
  96. Client = client,
  97. Device = deviceName,
  98. DeviceId = deviceId,
  99. Version = version,
  100. Token = token,
  101. IsAuthenticated = false,
  102. HasToken = false
  103. };
  104. if (string.IsNullOrWhiteSpace(token))
  105. {
  106. // Request doesn't contain a token.
  107. return authInfo;
  108. }
  109. authInfo.HasToken = true;
  110. var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
  111. await using (dbContext.ConfigureAwait(false))
  112. {
  113. var device = _deviceManager.GetDevices(
  114. new DeviceQuery
  115. {
  116. AccessToken = token
  117. }).Items.FirstOrDefault();
  118. if (device is not null)
  119. {
  120. authInfo.IsAuthenticated = true;
  121. var updateToken = false;
  122. // TODO: Remove these checks for IsNullOrWhiteSpace
  123. if (string.IsNullOrWhiteSpace(authInfo.Client))
  124. {
  125. authInfo.Client = device.AppName;
  126. }
  127. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  128. {
  129. authInfo.DeviceId = device.DeviceId;
  130. }
  131. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  132. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  133. if (string.IsNullOrWhiteSpace(authInfo.Device))
  134. {
  135. authInfo.Device = device.DeviceName;
  136. }
  137. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  138. {
  139. if (allowTokenInfoUpdate)
  140. {
  141. updateToken = true;
  142. device.DeviceName = authInfo.Device;
  143. }
  144. }
  145. if (string.IsNullOrWhiteSpace(authInfo.Version))
  146. {
  147. authInfo.Version = device.AppVersion;
  148. }
  149. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  150. {
  151. if (allowTokenInfoUpdate)
  152. {
  153. updateToken = true;
  154. device.AppVersion = authInfo.Version;
  155. }
  156. }
  157. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  158. {
  159. device.DateLastActivity = DateTime.UtcNow;
  160. updateToken = true;
  161. }
  162. authInfo.User = _userManager.GetUserById(device.UserId);
  163. if (updateToken)
  164. {
  165. await _deviceManager.UpdateDevice(device).ConfigureAwait(false);
  166. }
  167. }
  168. else
  169. {
  170. var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
  171. if (key is not null)
  172. {
  173. authInfo.IsAuthenticated = true;
  174. authInfo.Client = key.Name;
  175. authInfo.Token = key.AccessToken;
  176. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  177. {
  178. authInfo.DeviceId = _serverApplicationHost.SystemId;
  179. }
  180. if (string.IsNullOrWhiteSpace(authInfo.Device))
  181. {
  182. authInfo.Device = _serverApplicationHost.Name;
  183. }
  184. if (string.IsNullOrWhiteSpace(authInfo.Version))
  185. {
  186. authInfo.Version = _serverApplicationHost.ApplicationVersionString;
  187. }
  188. authInfo.IsApiKey = true;
  189. }
  190. }
  191. return authInfo;
  192. }
  193. }
  194. /// <summary>
  195. /// Gets the auth.
  196. /// </summary>
  197. /// <param name="httpReq">The HTTP request.</param>
  198. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  199. private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  200. {
  201. var auth = httpReq.Headers["X-Emby-Authorization"];
  202. if (string.IsNullOrEmpty(auth))
  203. {
  204. auth = httpReq.Headers[HeaderNames.Authorization];
  205. }
  206. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  207. }
  208. /// <summary>
  209. /// Gets the authorization.
  210. /// </summary>
  211. /// <param name="authorizationHeader">The authorization header.</param>
  212. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  213. private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  214. {
  215. var firstSpace = authorizationHeader.IndexOf(' ');
  216. // There should be at least two parts
  217. if (firstSpace == -1)
  218. {
  219. return null;
  220. }
  221. var name = authorizationHeader[..firstSpace];
  222. if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
  223. && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
  224. {
  225. return null;
  226. }
  227. // Remove up until the first space
  228. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  229. return GetParts(authorizationHeader);
  230. }
  231. /// <summary>
  232. /// Get the authorization header components.
  233. /// </summary>
  234. /// <param name="authorizationHeader">The authorization header.</param>
  235. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  236. public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
  237. {
  238. var result = new Dictionary<string, string>();
  239. var escaped = false;
  240. int start = 0;
  241. string key = string.Empty;
  242. int i;
  243. for (i = 0; i < authorizationHeader.Length; i++)
  244. {
  245. var token = authorizationHeader[i];
  246. if (token == '"' || token == ',')
  247. {
  248. // Applying a XOR logic to evaluate whether it is opening or closing a value
  249. escaped = (!escaped) == (token == '"');
  250. if (token == ',' && !escaped)
  251. {
  252. // Meeting a comma after a closing escape char means the value is complete
  253. if (start < i)
  254. {
  255. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  256. key = string.Empty;
  257. }
  258. start = i + 1;
  259. }
  260. }
  261. else if (!escaped && token == '=')
  262. {
  263. key = authorizationHeader[start.. i].Trim().ToString();
  264. start = i + 1;
  265. }
  266. }
  267. // Add last value
  268. if (start < i)
  269. {
  270. result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
  271. }
  272. return result;
  273. }
  274. }
  275. }