/// <summary> /// Checks if the current request is coming from an authenticated Umbraco User /// </summary> /// <param name="httpApp">The current HttpApplication</param> /// <returns>Whether or not the request is from an authenticated Umbraco User</returns> public static bool IsRequestAuthenticatedUmbracoUser(HttpApplication httpApp) { var httpContext = new HttpContextWrapper(httpApp.Context); var umbAuthTicket = httpContext.GetUmbracoAuthTicket(); return(httpContext.AuthenticateCurrentRequest(umbAuthTicket, true)); }
public bool Authorize(DashboardContext context) { var httpContextWrapper = new HttpContextWrapper(HttpContext.Current); var ticket = httpContextWrapper.GetUmbracoAuthTicket(); httpContextWrapper.AuthenticateCurrentRequest(ticket, true); var user = UmbracoContext.Current.Security.CurrentUser; return(user != null && user.AllowedSections.Contains("developer")); }
/// <inheritdoc /> public bool Authorize(DashboardContext context) { var httpContext = new HttpContextWrapper(HttpContext.Current); var ticket = httpContext.GetUmbracoAuthTicket(); httpContext.AuthenticateCurrentRequest(ticket, true); var user = Current.UmbracoContext.Security.CurrentUser; return(user != null && user.Groups.Any(g => g.Alias == Umbraco.Core.Constants.Security.AdminGroupAlias)); }
public bool Authorize(DashboardContext context) { var http = new HttpContextWrapper(HttpContext.Current); var ticket = http.GetUmbracoAuthTicket(); http.AuthenticateCurrentRequest(ticket, true); var user = UmbracoContext.Current.Security.CurrentUser; return(user != null && user.UserType.Alias == "admin"); }
public static bool AuthenticateTicket() { // see http://issues.umbraco.org/issue/U4-6342#comment=67-19466 (from http://issues.umbraco.org/issue/U4-6332) var http = new HttpContextWrapper(HttpContext.Current); var ticket = http.GetUmbracoAuthTicket(); if (ticket != null) { return(http.AuthenticateCurrentRequest(ticket, true)); } return(false); }
/// <summary> /// Authenticates the request by reading the FormsAuthentication cookie and setting the /// context and thread principle object /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void AuthenticateRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var http = new HttpContextWrapper(app.Context); //we need to determine if the path being requested is an umbraco path, if not don't do anything var settings = UmbracoSettings.GetSettings(); var backOfficeRoutePath = string.Concat(settings.UmbracoPaths.BackOfficePath, "/"); var installerRoutePath = string.Concat("Install", "/"); var routeUrl = ""; var routeData = RouteTable.Routes.GetRouteData(http); if (routeData != null) { var route = routeData.Route as Route; if (route != null) { routeUrl = route.Url; } } if (routeUrl.StartsWith(installerRoutePath, StringComparison.InvariantCultureIgnoreCase) || routeUrl.StartsWith(backOfficeRoutePath, StringComparison.InvariantCultureIgnoreCase)) { if (app.Context.User == null) { if (app.User != null) { //set the principal object app.Context.User = app.User; Thread.CurrentPrincipal = app.User; } else { var ticket = http.GetUmbracoAuthTicket(); if (ticket != null && !ticket.Expired && http.RenewUmbracoAuthTicket()) { //create the Umbraco user identity var identity = new UmbracoBackOfficeIdentity(ticket); //set the principal object var principal = new GenericPrincipal(identity, identity.Roles); app.Context.User = principal; Thread.CurrentPrincipal = principal; } } } } }
/// <summary> /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office /// so we'll force authentication. /// </summary> /// <param name="e"></param> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); //If this is not a back office request, then the module won't have authenticated it, in this case we // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false) { var http = new HttpContextWrapper(Context); var ticket = http.GetUmbracoAuthTicket(); http.AuthenticateCurrentRequest(ticket, true); } }
protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); if (PackageHelpers.UmbracoVersion != "7.2.2") { return; } // Handle authentication stuff to counteract bug in Umbraco 7.2.2 (see U4-6342) HttpContextWrapper http = new HttpContextWrapper(Context); FormsAuthenticationTicket ticket = http.GetUmbracoAuthTicket(); http.AuthenticateCurrentRequest(ticket, true); }
/// <summary> /// Checks if the request is authenticated, if it is it sets the thread culture to the currently logged in user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void AuthenticateRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var http = new HttpContextWrapper(app.Context); // do not process if client-side request if (http.Request.Url.IsClientSideRequest()) { return; } if (app.Request.Url.IsBackOfficeRequest() || app.Request.Url.IsInstallerRequest()) { var ticket = http.GetUmbracoAuthTicket(); if (ticket != null) { //create the Umbraco user identity var identity = ticket.CreateUmbracoIdentity(); if (identity != null) { //We'll leave setting custom identies/principals for 6.2, for now we'll just ensure that the cultures, etc.. are set ////set the principal object ////now we need to see if their session is still valid //var timeout = BasePage.GetTimeout(identity.UserContextId); //if (timeout > DateTime.Now.Ticks) //{ //var principal = new GenericPrincipal(identity, identity.Roles); ////It is actually not good enough to set this on the current app Context and the thread, it also needs //// to be set explicitly on the HttpContext.Current !! This is a strange web api thing that is actually //// an underlying fault of asp.net not propogating the User correctly. //if (HttpContext.Current != null) //{ // HttpContext.Current.User = principal; //} //app.Context.User = principal; //Thread.CurrentPrincipal = principal; //} //This is a back office/installer request, we will also set the culture/ui culture Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(identity.Culture); } } } }
/// <summary> /// Authorizes the user /// </summary> /// <param name="e"></param> /// <remarks> /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office /// so we'll force authentication. /// </remarks> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); //If this is not a back office request, then the module won't have authenticated it, in this case we // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false) { var http = new HttpContextWrapper(Context); var ticket = http.GetUmbracoAuthTicket(); http.AuthenticateCurrentRequest(ticket, true); } try { Security.ValidateCurrentUser(true); _hasValidated = true; if (!Security.ValidateUserApp(CurrentApp)) { var ex = new UserAuthorizationException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp)); LogHelper.Error <UmbracoEnsuredPage>(String.Format("Tried to access '{0}'", CurrentApp), ex); throw ex; } } catch { // Clear content as .NET transfers rendered content. Response.Clear(); // Some umbraco pages should not be loaded on timeout, but instead reload the main application in the top window. Like the treeview for instance if (RedirectToUmbraco) { Response.Redirect(SystemDirectories.Umbraco + "/logout.aspx?t=" + Security.GetSessionId(), true); } else { Response.Redirect(SystemDirectories.Umbraco + "/logout.aspx?redir=" + Server.UrlEncode(Request.RawUrl) + "&t=" + Security.GetSessionId(), true); } } }
/// <summary> /// Authorizes the user /// </summary> /// <param name="e"></param> /// <remarks> /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office /// so we'll force authentication. /// </remarks> protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); //If this is not a back office request, then the module won't have authenticated it, in this case we // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, Current.Configs.Global()) == false) { var http = new HttpContextWrapper(Context); var ticket = http.GetUmbracoAuthTicket(); http.AuthenticateCurrentRequest(ticket, true); } try { Security.ValidateCurrentUser(true); _hasValidated = true; if (!Security.ValidateUserApp(CurrentApp)) { var ex = new SecurityException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp)); Current.Logger.Error <UmbracoEnsuredPage>(ex, "Tried to access '{CurrentApp}'", CurrentApp); throw ex; } } catch { // Clear content as .NET transfers rendered content. Response.Clear(); // Ensure the person is definitely logged out UmbracoContext.Current.Security.ClearCurrentLogin(); // Redirect to the login page Response.Redirect(SystemDirectories.Umbraco + "#/login", true); } }
/// <inheritdoc /> public override bool Execute(IJob job, IConfiguration c) { AddMediaTypes(); job.UnwatchWebRequests(); if (!(c is MediaProtectionConfiguration config)) { job.WriteJournal(new JournalMessage("Error: Config passed into Media Protection was not of the correct type")); return(false); } if (!config.Enable || !job.Environment.Enable) { return(true); } if (config.EnableHotLinkingProtection) { var domains = new List <string>(); foreach (var domain in job.Environment.Domains) { try { var uriBuilder = new UriBuilder(domain.Name); domains.Add(uriBuilder.Host); } catch (Exception) { // Swallow } } var regex = new Regex("^(" + string.Join("|", config.HotLinkingProtectedDirectories) + ")", RegexOptions.IgnoreCase); job.WatchWebRequests(PipeLineStages.BeginRequest, regex, 30000, (count, httpApp) => { var referrer = httpApp.Request.UrlReferrer; if (referrer == null || String.IsNullOrWhiteSpace(referrer.Host) || referrer.Host.Equals(httpApp.Request.Url.Host, StringComparison.InvariantCultureIgnoreCase) || domains.Any(x => x.Equals(referrer.Host, StringComparison.InvariantCultureIgnoreCase))) { // This media is being accessed directly, // or from a browser that doesn't pass referrer info, // or from our own domain // so allow access return(new WatchResponse(WatchResponse.Cycles.Continue)); } job.WriteJournal(new JournalMessage($"Access was denied, {httpApp.Context.Request.UserHostAddress} from {referrer.Host} was trying to hotlink your media assets")); // Someone is trying to hotlink our media httpApp.Response.StatusCode = (int)HttpStatusCode.Forbidden; httpApp.Response.End(); return(new WatchResponse(WatchResponse.Cycles.Stop)); }); } if (!config.EnableMembersOnlyMedia) { return(true); } var mediaFolder = VirtualPathUtility.ToAbsolute(new Uri(Umbraco.Core.IO.SystemDirectories.Media, UriKind.Relative).ToString()) + "/"; job.WatchWebRequests(PipeLineStages.BeginRequest, new Regex(mediaFolder, RegexOptions.IgnoreCase), 30100, (count, httpApp) => { var httpContext = new HttpContextWrapper(httpApp.Context); var umbAuthTicket = httpContext.GetUmbracoAuthTicket(); // If we have logged in as a backend user, then allow all access if (httpContext.AuthenticateCurrentRequest(umbAuthTicket, true)) { return(new WatchResponse(WatchResponse.Cycles.Continue)); } var filename = httpApp.Request.Url.LocalPath; var secureMedia = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem(CacheKey + "F" + filename, () => { var umbracoContext = Umbraco.Web.UmbracoContext.Current; if (umbracoContext == null) { var newHttpContext = new HttpContextWrapper(HttpContext.Current); umbracoContext = UmbracoContext.EnsureContext( newHttpContext, ApplicationContext.Current, new Umbraco.Web.Security.WebSecurity(newHttpContext, ApplicationContext.Current), UmbracoConfig.For.UmbracoSettings(), UrlProviderResolver.Current.Providers, true); } var mediaService = new UmbracoMediaService(umbracoContext); var mediaId = mediaService.Id(filename); if (mediaId == null) { return(false); } var pathIdKeys = new List <string>(); object accessRights = null; var traverseId = mediaId; // We traverse up the ancestors until we either hit the root, or find our access rights // from either our special alias value or a cache value from a previous request while (traverseId != null) { var cacheIdKey = CacheKey + "I" + traverseId; accessRights = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem(cacheIdKey); if (accessRights != null) { break; } pathIdKeys.Add(cacheIdKey); var memberOnly = mediaService.Value((int)traverseId, MemberOnlyAlias); if (memberOnly == null) { accessRights = false; } else { switch (memberOnly) { case bool _: accessRights = (bool)memberOnly ? 1 : 0; break; case int _: accessRights = (int)memberOnly != 0; break; case string _: // Is a MNTP that states which member groups can access this media item try { accessRights = ((string)memberOnly).Split(',').Select(int.Parse).ToArray(); } catch (Exception) { // Swallow conversion issues, and continue processing } break; } break; } traverseId = mediaService.ParentId((int)traverseId); } if (accessRights == null) { accessRights = false; } // Give our descendants the same access rights as us foreach (var key in pathIdKeys) { ApplicationContext.Current.ApplicationCache.RuntimeCache.InsertCacheItem(key, () => accessRights, _cacheLength); } return(accessRights); }, _cacheLength); if (secureMedia is bool b) { if (b == false || (httpApp.Context.User != null && httpApp.Context.User.Identity.IsAuthenticated)) { // They are allowed to view this media return(new WatchResponse(WatchResponse.Cycles.Continue)); } } if (secureMedia is int[] ints) { if (ints.Length == 0) { // They are allowed to view this media return(new WatchResponse(WatchResponse.Cycles.Continue)); } if (httpApp.Context.User.Identity.IsAuthenticated) { // TODO: Need to handle when security is member group based return(new WatchResponse(WatchResponse.Cycles.Continue)); } } job.WriteJournal(new JournalMessage($"An unauthenticated member tried to access {filename} with IP Address: {httpApp.Context.Request.UserHostAddress}")); // You need to be logged in or be a member of the correct member group to see this media httpApp.Response.StatusCode = (int)HttpStatusCode.Forbidden; httpApp.Response.End(); return(new WatchResponse(WatchResponse.Cycles.Stop)); }); return(true); }
public static bool IsUserLoggedInUmbraco(this HttpContextWrapper httpContextWrapper) => httpContextWrapper?.GetUmbracoAuthTicket()?.Identity is UmbracoBackOfficeIdentity;