AuthorizationContext.cs 12 KB

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