AuthService.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Controller.Session;
  5. using ServiceStack;
  6. using ServiceStack.Auth;
  7. using ServiceStack.Web;
  8. using System;
  9. using System.Collections.Specialized;
  10. using System.Linq;
  11. namespace MediaBrowser.Server.Implementations.HttpServer.Security
  12. {
  13. public class AuthService : IAuthService
  14. {
  15. public AuthService(IUserManager userManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext)
  16. {
  17. AuthorizationContext = authorizationContext;
  18. SessionManager = sessionManager;
  19. UserManager = userManager;
  20. }
  21. public IUserManager UserManager { get; private set; }
  22. public ISessionManager SessionManager { get; private set; }
  23. public IAuthorizationContext AuthorizationContext { get; private set; }
  24. /// <summary>
  25. /// Restrict authentication to a specific <see cref="IAuthProvider"/>.
  26. /// For example, if this attribute should only permit access
  27. /// if the user is authenticated with <see cref="BasicAuthProvider"/>,
  28. /// you should set this property to <see cref="BasicAuthProvider.Name"/>.
  29. /// </summary>
  30. public string Provider { get; set; }
  31. /// <summary>
  32. /// Redirect the client to a specific URL if authentication failed.
  33. /// If this property is null, simply `401 Unauthorized` is returned.
  34. /// </summary>
  35. public string HtmlRedirect { get; set; }
  36. public void Authenticate(IRequest req, IResponse res, object requestDto)
  37. {
  38. if (HostContext.HasValidAuthSecret(req))
  39. return;
  40. ExecuteBasic(req, res, requestDto); //first check if session is authenticated
  41. if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)
  42. ValidateUser(req);
  43. }
  44. private void ValidateUser(IRequest req)
  45. {
  46. User user = null;
  47. //This code is executed before the service
  48. var auth = AuthorizationContext.GetAuthorizationInfo(req);
  49. if (auth != null)
  50. {
  51. if (!string.IsNullOrWhiteSpace(auth.UserId))
  52. {
  53. var userId = auth.UserId;
  54. user = UserManager.GetUserById(new Guid(userId));
  55. }
  56. string deviceId = auth.DeviceId;
  57. string device = auth.Device;
  58. string client = auth.Client;
  59. string version = auth.Version;
  60. if (!string.IsNullOrEmpty(client) && !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(version))
  61. {
  62. var remoteEndPoint = req.RemoteIp;
  63. SessionManager.LogSessionActivity(client, version, deviceId, device, remoteEndPoint, user);
  64. }
  65. }
  66. if (user == null || user.Configuration.IsDisabled)
  67. {
  68. throw new UnauthorizedAccessException("Unauthorized access.");
  69. }
  70. }
  71. private void ExecuteBasic(IRequest req, IResponse res, object requestDto)
  72. {
  73. if (AuthenticateService.AuthProviders == null)
  74. throw new InvalidOperationException(
  75. "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");
  76. var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
  77. this.Provider.IsNullOrEmpty()
  78. || x.Provider == this.Provider).ToList();
  79. if (matchingOAuthConfigs.Count == 0)
  80. {
  81. res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
  82. .Fmt(this.Provider ?? "any"));
  83. res.EndRequest();
  84. }
  85. matchingOAuthConfigs.OfType<IAuthWithRequest>()
  86. .Each(x => x.PreAuthenticate(req, res));
  87. var session = req.GetSession();
  88. if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
  89. {
  90. if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;
  91. AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
  92. }
  93. }
  94. private void LogRequest()
  95. {
  96. }
  97. protected bool DoHtmlRedirectIfConfigured(IRequest req, IResponse res, bool includeRedirectParam = false)
  98. {
  99. var htmlRedirect = this.HtmlRedirect ?? AuthenticateService.HtmlRedirect;
  100. if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(MimeTypes.Html))
  101. {
  102. DoHtmlRedirect(htmlRedirect, req, res, includeRedirectParam);
  103. return true;
  104. }
  105. return false;
  106. }
  107. public static void DoHtmlRedirect(string redirectUrl, IRequest req, IResponse res, bool includeRedirectParam)
  108. {
  109. var url = req.ResolveAbsoluteUrl(redirectUrl);
  110. if (includeRedirectParam)
  111. {
  112. var absoluteRequestPath = req.ResolveAbsoluteUrl("~" + req.PathInfo + ToQueryString(req.QueryString));
  113. url = url.AddQueryParam(HostContext.ResolveLocalizedString(LocalizedStrings.Redirect), absoluteRequestPath);
  114. }
  115. res.RedirectToUrl(url);
  116. }
  117. private static string ToQueryString(INameValueCollection queryStringCollection)
  118. {
  119. return ToQueryString((NameValueCollection)queryStringCollection.Original);
  120. }
  121. private static string ToQueryString(NameValueCollection queryStringCollection)
  122. {
  123. if (queryStringCollection == null || queryStringCollection.Count == 0)
  124. return String.Empty;
  125. return "?" + queryStringCollection.ToFormUrlEncoded();
  126. }
  127. }
  128. }