2
0

AuthorizationContext.cs 12 KB

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