AuthorizationContext.cs 10 KB

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