AuthorizationContext.cs 11 KB

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