AuthorizationContext.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Extensions;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Net;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.Net.Http.Headers;
  12. namespace Jellyfin.Server.Implementations.Security
  13. {
  14. public class AuthorizationContext : IAuthorizationContext
  15. {
  16. private readonly JellyfinDb _jellyfinDb;
  17. private readonly IUserManager _userManager;
  18. public AuthorizationContext(JellyfinDb jellyfinDb, IUserManager userManager)
  19. {
  20. _jellyfinDb = jellyfinDb;
  21. _userManager = userManager;
  22. }
  23. public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
  24. {
  25. if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached != null)
  26. {
  27. return Task.FromResult((AuthorizationInfo)cached);
  28. }
  29. return GetAuthorization(requestContext);
  30. }
  31. public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
  32. {
  33. var auth = GetAuthorizationDictionary(requestContext);
  34. var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
  35. return authInfo;
  36. }
  37. /// <summary>
  38. /// Gets the authorization.
  39. /// </summary>
  40. /// <param name="httpReq">The HTTP req.</param>
  41. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  42. private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpReq)
  43. {
  44. var auth = GetAuthorizationDictionary(httpReq);
  45. var authInfo = await GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query).ConfigureAwait(false);
  46. httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
  47. return authInfo;
  48. }
  49. private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
  50. IReadOnlyDictionary<string, string>? auth,
  51. IHeaderDictionary headers,
  52. IQueryCollection queryString)
  53. {
  54. string? deviceId = null;
  55. string? deviceName = null;
  56. string? client = null;
  57. string? version = null;
  58. string? token = null;
  59. if (auth != null)
  60. {
  61. auth.TryGetValue("DeviceId", out deviceId);
  62. auth.TryGetValue("Device", out deviceName);
  63. auth.TryGetValue("Client", out client);
  64. auth.TryGetValue("Version", out version);
  65. auth.TryGetValue("Token", out token);
  66. }
  67. #pragma warning disable CA1508
  68. // headers can return StringValues.Empty
  69. if (string.IsNullOrEmpty(token))
  70. {
  71. token = headers["X-Emby-Token"];
  72. }
  73. if (string.IsNullOrEmpty(token))
  74. {
  75. token = headers["X-MediaBrowser-Token"];
  76. }
  77. if (string.IsNullOrEmpty(token))
  78. {
  79. token = queryString["ApiKey"];
  80. }
  81. // TODO deprecate this query parameter.
  82. if (string.IsNullOrEmpty(token))
  83. {
  84. token = queryString["api_key"];
  85. }
  86. var authInfo = new AuthorizationInfo
  87. {
  88. Client = client,
  89. Device = deviceName,
  90. DeviceId = deviceId,
  91. Version = version,
  92. Token = token,
  93. IsAuthenticated = false,
  94. HasToken = false
  95. };
  96. if (string.IsNullOrWhiteSpace(token))
  97. {
  98. // Request doesn't contain a token.
  99. return authInfo;
  100. }
  101. #pragma warning restore CA1508
  102. authInfo.HasToken = true;
  103. var device = await _jellyfinDb.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);
  104. if (device != null)
  105. {
  106. authInfo.IsAuthenticated = true;
  107. }
  108. if (device != null)
  109. {
  110. var updateToken = false;
  111. // TODO: Remove these checks for IsNullOrWhiteSpace
  112. if (string.IsNullOrWhiteSpace(authInfo.Client))
  113. {
  114. authInfo.Client = device.AppName;
  115. }
  116. if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
  117. {
  118. authInfo.DeviceId = device.DeviceId;
  119. }
  120. // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
  121. var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
  122. if (string.IsNullOrWhiteSpace(authInfo.Device))
  123. {
  124. authInfo.Device = device.DeviceName;
  125. }
  126. else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
  127. {
  128. if (allowTokenInfoUpdate)
  129. {
  130. updateToken = true;
  131. device.DeviceName = authInfo.Device;
  132. }
  133. }
  134. if (string.IsNullOrWhiteSpace(authInfo.Version))
  135. {
  136. authInfo.Version = device.AppVersion;
  137. }
  138. else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
  139. {
  140. if (allowTokenInfoUpdate)
  141. {
  142. updateToken = true;
  143. device.AppVersion = authInfo.Version;
  144. }
  145. }
  146. if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
  147. {
  148. device.DateLastActivity = DateTime.UtcNow;
  149. updateToken = true;
  150. }
  151. if (!device.UserId.Equals(Guid.Empty))
  152. {
  153. authInfo.User = _userManager.GetUserById(device.UserId);
  154. authInfo.IsApiKey = false;
  155. }
  156. else
  157. {
  158. authInfo.IsApiKey = true;
  159. }
  160. if (updateToken)
  161. {
  162. _jellyfinDb.Devices.Update(device);
  163. await _jellyfinDb.SaveChangesAsync().ConfigureAwait(false);
  164. }
  165. }
  166. return authInfo;
  167. }
  168. /// <summary>
  169. /// Gets the auth.
  170. /// </summary>
  171. /// <param name="httpReq">The HTTP req.</param>
  172. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  173. private static Dictionary<string, string>? GetAuthorizationDictionary(HttpContext httpReq)
  174. {
  175. var auth = httpReq.Request.Headers["X-Emby-Authorization"];
  176. if (string.IsNullOrEmpty(auth))
  177. {
  178. auth = httpReq.Request.Headers[HeaderNames.Authorization];
  179. }
  180. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  181. }
  182. /// <summary>
  183. /// Gets the auth.
  184. /// </summary>
  185. /// <param name="httpReq">The HTTP req.</param>
  186. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  187. private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
  188. {
  189. var auth = httpReq.Headers["X-Emby-Authorization"];
  190. if (string.IsNullOrEmpty(auth))
  191. {
  192. auth = httpReq.Headers[HeaderNames.Authorization];
  193. }
  194. return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
  195. }
  196. /// <summary>
  197. /// Gets the authorization.
  198. /// </summary>
  199. /// <param name="authorizationHeader">The authorization header.</param>
  200. /// <returns>Dictionary{System.StringSystem.String}.</returns>
  201. private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
  202. {
  203. var firstSpace = authorizationHeader.IndexOf(' ');
  204. // There should be at least two parts
  205. if (firstSpace == -1)
  206. {
  207. return null;
  208. }
  209. var name = authorizationHeader[..firstSpace];
  210. if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
  211. && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
  212. {
  213. return null;
  214. }
  215. authorizationHeader = authorizationHeader[(firstSpace + 1)..];
  216. var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  217. foreach (var item in authorizationHeader.Split(','))
  218. {
  219. var trimmedItem = item.Trim();
  220. var firstEqualsSign = trimmedItem.IndexOf('=');
  221. if (firstEqualsSign > 0)
  222. {
  223. var key = trimmedItem[..firstEqualsSign].ToString();
  224. var value = NormalizeValue(trimmedItem[(firstEqualsSign + 1)..].Trim('"').ToString());
  225. result[key] = value;
  226. }
  227. }
  228. return result;
  229. }
  230. private static string NormalizeValue(string value)
  231. {
  232. return string.IsNullOrEmpty(value) ? value : WebUtility.HtmlEncode(value);
  233. }
  234. }
  235. }