AuthorizationContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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.Database.Implementations;
  8. using Jellyfin.Extensions;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Devices;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Net;
  14. using Microsoft.AspNetCore.Http;
  15. using Microsoft.EntityFrameworkCore;
  16. using Microsoft.Net.Http.Headers;
  17. namespace Jellyfin.Server.Implementations.Security
  18. {
  19. public class AuthorizationContext : IAuthorizationContext
  20. {
  21. private readonly IDbContextFactory<JellyfinDbContext> _jellyfinDbProvider;
  22. private readonly IUserManager _userManager;
  23. private readonly IDeviceManager _deviceManager;
  24. private readonly IServerApplicationHost _serverApplicationHost;
  25. private readonly IServerConfigurationManager _configurationManager;
  26. public AuthorizationContext(
  27. IDbContextFactory<JellyfinDbContext> jellyfinDb,
  28. IUserManager userManager,
  29. IDeviceManager deviceManager,
  30. IServerApplicationHost serverApplicationHost,
  31. IServerConfigurationManager configurationManager)
  32. {
  33. _jellyfinDbProvider = jellyfinDb;
  34. _userManager = userManager;
  35. _deviceManager = deviceManager;
  36. _serverApplicationHost = serverApplicationHost;
  37. _configurationManager = configurationManager;
  38. }
  39. public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
  40. {
  41. if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached is not null)
  42. {
  43. return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
  44. }
  45. return GetAuthorization(requestContext);
  46. }
  47. public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
  48. {
  49. var auth = GetAuthorizationDictionary(requestContext);
  50. var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
  51. return authInfo;
  52. }
  53. /// <summary>
  54. /// Gets the authorization.
  55. /// </summary>
  56. /// <param name="httpContext">The HTTP context.</param>
  57. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  58. private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpContext)
  59. {
  60. var authInfo = await GetAuthorizationInfo(httpContext.Request).ConfigureAwait(false);
  61. httpContext.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  62. return authInfo;
  63. }
  64. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  65. Dictionary<string, string>? auth,
  66. IHeaderDictionary headers,
  67. IQueryCollection queryString)
  68. {
  69. string? deviceId = null;
  70. string? deviceName = null;
  71. string? client = null;
  72. string? version = null;
  73. string? token = null;
  74. if (auth is not null)
  75. {
  76. auth.TryGetValue("DeviceId", out deviceId);
  77. auth.TryGetValue("Device", out deviceName);
  78. auth.TryGetValue("Client", out client);
  79. auth.TryGetValue("Version", out version);
  80. auth.TryGetValue("Token", out token);
  81. }
  82. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  83. {
  84. token = headers["X-Emby-Token"];
  85. }
  86. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  87. {
  88. token = headers["X-MediaBrowser-Token"];
  89. }
  90. if (string.IsNullOrEmpty(token))
  91. {
  92. token = queryString["ApiKey"];
  93. }
  94. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(token))
  95. {
  96. token = queryString["api_key"];
  97. }
  98. var authInfo = new AuthorizationInfo
  99. {
  100. Client = client,
  101. Device = deviceName,
  102. DeviceId = deviceId,
  103. Version = version,
  104. Token = token,
  105. IsAuthenticated = false
  106. };
  107. if (!authInfo.HasToken)
  108. {
  109. // Request doesn't contain a token.
  110. return authInfo;
  111. }
  112. var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
  113. await using (dbContext.ConfigureAwait(false))
  114. {
  115. var device = _deviceManager.GetDevices(
  116. new DeviceQuery { AccessToken = token }).Items.FirstOrDefault();
  117. if (device is not null)
  118. {
  119. authInfo.IsAuthenticated = true;
  120. var updateToken = false;
  121. // TODO: Remove these checks for IsNullOrWhiteSpace
  122. if (string.IsNullOrWhiteSpace(authInfo.Client))
  123. {
  124. authInfo.Client = device.AppName;
  125. }
  126. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  127. {
  128. authInfo.DeviceId = device.DeviceId;
  129. }
  130. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  131. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  132. if (string.IsNullOrWhiteSpace(authInfo.Device))
  133. {
  134. authInfo.Device = device.DeviceName;
  135. }
  136. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  137. {
  138. if (allowTokenInfoUpdate)
  139. {
  140. updateToken = true;
  141. device.DeviceName = authInfo.Device;
  142. }
  143. }
  144. if (string.IsNullOrWhiteSpace(authInfo.Version))
  145. {
  146. authInfo.Version = device.AppVersion;
  147. }
  148. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  149. {
  150. if (allowTokenInfoUpdate)
  151. {
  152. updateToken = true;
  153. device.AppVersion = authInfo.Version;
  154. }
  155. }
  156. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  157. {
  158. device.DateLastActivity = DateTime.UtcNow;
  159. updateToken = true;
  160. }
  161. authInfo.User = _userManager.GetUserById(device.UserId);
  162. if (updateToken)
  163. {
  164. await _deviceManager.UpdateDevice(device).ConfigureAwait(false);
  165. }
  166. }
  167. else
  168. {
  169. var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
  170. if (key is not null)
  171. {
  172. authInfo.IsAuthenticated = true;
  173. authInfo.Client = key.Name;
  174. authInfo.Token = key.AccessToken;
  175. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  176. {
  177. authInfo.DeviceId = _serverApplicationHost.SystemId;
  178. }
  179. if (string.IsNullOrWhiteSpace(authInfo.Device))
  180. {
  181. authInfo.Device = _serverApplicationHost.Name;
  182. }
  183. if (string.IsNullOrWhiteSpace(authInfo.Version))
  184. {
  185. authInfo.Version = _serverApplicationHost.ApplicationVersionString;
  186. }
  187. authInfo.IsApiKey = true;
  188. }
  189. }
  190. return authInfo;
  191. }
  192. }
  193. /// <summary>
  194. /// Gets the auth.
  195. /// </summary>
  196. /// <param name="httpReq">The HTTP request.</param>
  197. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  198. private Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  199. {
  200. var auth = httpReq.Headers[HeaderNames.Authorization];
  201. if (_configurationManager.Configuration.EnableLegacyAuthorization && string.IsNullOrEmpty(auth))
  202. {
  203. auth = httpReq.Headers["X-Emby-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 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. var validName = name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase);
  222. validName = validName || (_configurationManager.Configuration.EnableLegacyAuthorization && name.Equals("Emby", StringComparison.OrdinalIgnoreCase));
  223. if (!validName)
  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. }