AuthService.cs 6.1 KB

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