public void Create_From_Claims_Identity()
        {
            var sessionId      = Guid.NewGuid().ToString();
            var claimsIdentity = new ClaimsIdentity(new[]
            {
                //This is the id that 'identity' uses to check for the user id
                new Claim(ClaimTypes.NameIdentifier, "1234", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                //This is the id that 'identity' uses to check for the username
                new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.GivenName, "hello world", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.StartContentNodeIdClaimType, "-1", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(Constants.Security.StartMediaNodeIdClaimType, "5543", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(Constants.Security.AllowedApplicationsClaimType, "content", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.AllowedApplicationsClaimType, "media", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.Locality, "en-us", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.SessionIdClaimType, sessionId, Constants.Security.SessionIdClaimType, TestIssuer, TestIssuer),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin", ClaimValueTypes.String, TestIssuer, TestIssuer),
            });

            var backofficeIdentity = UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity);

            Assert.AreEqual("1234", backofficeIdentity.Id);
            Assert.AreEqual(sessionId, backofficeIdentity.SessionId);
            Assert.AreEqual("testing", backofficeIdentity.Username);
            Assert.AreEqual("hello world", backofficeIdentity.RealName);
            Assert.AreEqual(-1, backofficeIdentity.StartContentNode);
            Assert.AreEqual(5543, backofficeIdentity.StartMediaNode);
            Assert.IsTrue(new[] { "content", "media" }.SequenceEqual(backofficeIdentity.AllowedApplications));
            Assert.AreEqual("en-us", backofficeIdentity.Culture);
            Assert.IsTrue(new[] { "admin" }.SequenceEqual(backofficeIdentity.Roles));

            Assert.AreEqual(10, backofficeIdentity.Claims.Count());
        }
        public void Initialize()
        {
            _controller = new DummyController();

            var userData = @"{
                'Id' : '6C50D4C1-B608-4EFA-B488-C95DBC6F9BA6',
                'Roles' : [ 'Editor' ],
                'SessionTimeout' : 60,
                'RealName' : 'Dummy User',
                'StartContentNode' : '',
                'StartMediaNode' : '',
                'AllowedApplications' : [ 'Content', 'Media' ]
            }";

            var ticket   = new FormsAuthenticationTicket(1, "DummyUser", DateTime.Now.AddHours(-1), DateTime.Now.AddHours(1), false, userData);
            var identity = new UmbracoBackOfficeIdentity(ticket);

            var user = Substitute.For <IPrincipal>();

            user.Identity.Returns(identity);

            var httpContext = Substitute.For <HttpContextBase>();

            httpContext.User.Returns(user);

            var routeData         = new RouteData();
            var context           = new RequestContext(httpContext, routeData);
            var controllerContext = new ControllerContext(context, _controller);

            _controller.ControllerContext = controllerContext;
        }
        public void Create_With_Claims_And_User_Data()
        {
            var sessionId = Guid.NewGuid().ToString();
            var userData  = new UserData(sessionId)
            {
                AllowedApplications = new[] { "content", "media" },
                Culture             = "en-us",
                Id               = 1234,
                RealName         = "hello world",
                Roles            = new[] { "admin" },
                StartContentNode = -1,
                StartMediaNode   = 654,
                Username         = "******"
            };

            var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer)
            });

            var backofficeIdentity = new UmbracoBackOfficeIdentity(claimsIdentity, userData);

            Assert.AreEqual(13, backofficeIdentity.Claims.Count());
        }
        /// <summary>
        /// Create a ClaimsIdentity from a user
        /// </summary>
        /// <param name="manager"/><param name="user"/><param name="authenticationType"/>
        /// <returns/>
        public override async Task <ClaimsIdentity> CreateAsync(UserManager <T, int> manager, T user, string authenticationType)
        {
            var baseIdentity = await base.CreateAsync(manager, user, authenticationType);

            // now we can flow any custom claims that the actual user has currently assigned which could be done in the OnExternalLogin callback
            foreach (var claim in user.Claims)
            {
                baseIdentity.AddClaim(new Claim(claim.ClaimType, claim.ClaimValue));
            }

            var umbracoIdentity = new UmbracoBackOfficeIdentity(baseIdentity,
                                                                user.Id,
                                                                user.UserName,
                                                                user.Name,
                                                                user.CalculatedContentStartNodeIds,
                                                                user.CalculatedMediaStartNodeIds,
                                                                user.Culture,
                                                                //NOTE - there is no session id assigned here, this is just creating the identity, a session id will be generated when the cookie is written
                                                                Guid.NewGuid().ToString(),
                                                                user.SecurityStamp,
                                                                user.AllowedSections,
                                                                user.Roles.Select(x => x.RoleId).ToArray());

            return(umbracoIdentity);
        }
        /// <summary>
        /// Unprotects the cookie
        /// </summary>
        /// <param name="protectedText"></param>
        /// <returns></returns>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            FormsAuthenticationTicket decrypt;

            try
            {
                decrypt = FormsAuthentication.Decrypt(protectedText);
                if (decrypt == null)
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            var identity = new UmbracoBackOfficeIdentity(decrypt);

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties
            {
                ExpiresUtc   = decrypt.Expiration.ToUniversalTime(),
                IssuedUtc    = decrypt.IssueDate.ToUniversalTime(),
                IsPersistent = decrypt.IsPersistent,
                AllowRefresh = true
            });

            return(ticket);
        }
        /// <summary>
        /// Unprotects the cookie
        /// </summary>
        /// <param name="protectedText"></param>
        /// <returns></returns>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            AuthenticationTicket decrypt;

            try
            {
                decrypt = _ticketDataFormat.Unprotect(protectedText);
                if (decrypt == null)
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            UmbracoBackOfficeIdentity identity;

            try
            {
                identity = UmbracoBackOfficeIdentity.FromClaimsIdentity(decrypt.Identity);
            }
            catch (Exception)
            {
                //if it cannot be created return null, will be due to serialization errors in user data most likely due to corrupt cookies or cookies
                //for previous versions of Umbraco
                return(null);
            }

            //return the ticket with a UmbracoBackOfficeIdentity
            var ticket = new AuthenticationTicket(identity, decrypt.Properties);

            return(ticket);
        }
        public void Create_From_Claims_Identity_Missing_Required_Claim()
        {
            var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "1234", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
            });

            Assert.Throws <InvalidOperationException>(() => UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity));
        }
        public void Clone()
        {
            var sessionId = Guid.NewGuid().ToString();

            var identity = new UmbracoBackOfficeIdentity(
                1234, "testing", "hello world", new[] { 654 }, new[] { 654 }, "en-us", sessionId, sessionId, new[] { "content", "media" }, new[] { "admin" });

            var cloned = identity.Clone();

            Assert.AreEqual(10, cloned.Claims.Count());
        }
            protected override Task <AuthenticationTicket> AuthenticateCoreAsync()
            {
                var sessionId = Guid.NewGuid().ToString();
                var identity  = new UmbracoBackOfficeIdentity(
                    -1, "admin", "Admin", new [] { -1 }, new[] { -1 }, "en-US", sessionId, sessionId, new[] { "content", "media", "members" }, new[] { "admin" });

                return(Task.FromResult(new AuthenticationTicket(identity,
                                                                new AuthenticationProperties()
                {
                    ExpiresUtc = DateTime.Now.AddDays(1)
                })));
            }
예제 #10
0
        public async Task Get_Root_Result_With_Custom_Start_Nodes()
        {
            //represents the node(s) that the user will receive as their root based on their custom start node
            var rootNodes = ModelMocks.SimpleMockedContent(123, 456);

            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 456);

                var mockContentService = Mock.Get(testServices.ServiceContext.ContentService);
                mockContentService.Setup(x => x.GetByIds(It.IsAny <int[]>())).Returns(new[]
                {
                    rootNodes
                });

                mockContentService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedContent(789, 123) });
                mockContentService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedContent(321, 456) });
            });

            var djson = await Get_Root_Result(app =>
            {
                //we are doing a custom authz for this call so need to change the startup process

                var identity = new UmbracoBackOfficeIdentity(
                    new UserData(Guid.NewGuid().ToString())
                {
                    Id    = 0,
                    Roles = new[] { "admin" },
                    AllowedApplications = new[] { "content", "media", "members" },
                    Culture             = "en-US",
                    RealName            = "Admin",
                    StartContentNodes   = new[] { 456 },
                    StartMediaNodes     = new[] { -1 },
                    Username            = "******",
                    SessionId           = Guid.NewGuid().ToString(),
                    SecurityStamp       = Guid.NewGuid().ToString()
                });

                var httpConfig = startup.UseTestWebApiConfiguration(app);
                app.AuthenticateEverything(new AuthenticateEverythingAuthenticationOptions(identity));
                app.UseUmbracoRestApi(startup.ApplicationContext);
                app.UseWebApi(httpConfig);
            }, RouteConstants.ContentSegment);

            Assert.AreEqual(1, djson["_links"]["content"].Count());
            Assert.AreEqual($"/umbraco/rest/v1/content/{123.ToGuid()}", djson["_links"]["content"]["href"].Value <string>());
            Assert.AreEqual(1, djson["_embedded"]["content"].Count());
            Assert.AreEqual(rootNodes.Key, (Guid)djson["_embedded"]["content"].First["id"]);
        }
        public void Create_With_Claims_And_User_Data()
        {
            var sessionId = Guid.NewGuid().ToString();

            var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim("TestClaim1", "test", ClaimValueTypes.Integer32, TestIssuer, TestIssuer)
            });

            var identity = new UmbracoBackOfficeIdentity(claimsIdentity,
                                                         1234, "testing", "hello world", new[] { 654 }, new[] { 654 }, "en-us", sessionId, sessionId, new[] { "content", "media" }, new[] { "admin" });

            Assert.AreEqual(12, identity.Claims.Count());
        }
        public void Create_With_User_Data()
        {
            var sessionId = Guid.NewGuid().ToString();
            var userData  = new UserData(sessionId)
            {
                AllowedApplications = new[] { "content", "media" },
                Culture             = "en-us",
                Id              = 1234,
                RealName        = "hello world",
                Roles           = new[] { "admin" },
                StartMediaNodes = new [] { 654 },
                Username        = "******"
            };

            var identity = new UmbracoBackOfficeIdentity(userData);

            Assert.AreEqual(11, identity.Claims.Count());
        }
예제 #13
0
        public bool TryFindContent(PublishedRequest contentRequest)
        {
            // handle all requests beginning /website...
            var                       path       = contentRequest.Uri.AbsolutePath;
            HttpContextBase           wrapper    = new HttpContextWrapper(HttpContext.Current);
            UmbracoBackOfficeIdentity user       = wrapper.GetCurrentIdentity(true);
            bool                      isLoggedIn = user != null;

            if (!isLoggedIn)
            {
                if (path.StartsWith("/" + StandingData.UmbracoRootFolderUrl))
                {
                    contentRequest.Is404 = true;
                    HttpContext.Current.Response.Redirect(path.Replace("/" + StandingData.UmbracoRootFolderUrl, ""));
                }
            }

            return(true);
        }
        //protected override ApplicationContext CreateApplicationContext()
        //{
        //    serviceContext = MockHelper.GetMockedServiceContext();
        //    return new ApplicationContext(
        //        new DatabaseContext(new Mock<IDatabaseFactory>().Object, Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test"),
        //        serviceContext,
        //        CacheHelper.CreateDisabledCacheHelper(),
        //        new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())
        //    );
        //}

        private UmbracoBackOfficeIdentity CreateIdentity(int userId)
        {
            var sessionId = Guid.NewGuid().ToString();
            var userData  = new UserData(sessionId)
            {
                AllowedApplications = new[] { "content", "media" },
                Culture             = "en-us",
                Id                = userId,
                RealName          = "hello world",
                Roles             = new[] { "admin" },
                StartContentNodes = new[] { -1 },
                StartMediaNodes   = new [] { 654 },
                Username          = "******"
            };

            var identity = new UmbracoBackOfficeIdentity(userData);

            return(identity);
        }
        /// <summary>
        /// Create a ClaimsIdentity from a user
        /// </summary>
        /// <param name="manager"/><param name="user"/><param name="authenticationType"/>
        /// <returns/>
        public override async Task <ClaimsIdentity> CreateAsync(UserManager <T, int> manager, T user, string authenticationType)
        {
            var baseIdentity = await base.CreateAsync(manager, user, authenticationType);

            var umbracoIdentity = new UmbracoBackOfficeIdentity(baseIdentity,
                                                                user.Id,
                                                                user.UserName,
                                                                user.Name,
                                                                user.CalculatedContentStartNodeIds,
                                                                user.CalculatedMediaStartNodeIds,
                                                                user.Culture,
                                                                //NOTE - there is no session id assigned here, this is just creating the identity, a session id will be generated when the cookie is written
                                                                Guid.NewGuid().ToString(),
                                                                user.SecurityStamp,
                                                                user.AllowedSections,
                                                                user.Roles.Select(x => x.RoleId).ToArray());

            return(umbracoIdentity);
        }
예제 #16
0
            protected override Task <AuthenticationTicket> AuthenticateCoreAsync()
            {
                var identity = new UmbracoBackOfficeIdentity(
                    new UserData(Guid.NewGuid().ToString())
                {
                    Id    = 0,
                    Roles = new[] { "admin" },
                    AllowedApplications = new[] { "content", "media", "members" },
                    Culture             = "en-US",
                    RealName            = "Admin",
                    Username            = "******"
                });

                return(Task.FromResult(new AuthenticationTicket(identity,
                                                                new AuthenticationProperties()
                {
                    ExpiresUtc = DateTime.Now.AddDays(1)
                })));
            }
        public AuthenticateEverythingAuthenticationOptions()
            : base("AuthenticateEverything")
        {
            AuthenticationMode = AuthenticationMode.Active;
            var identity = new UmbracoBackOfficeIdentity(
                new UserData(Guid.NewGuid().ToString())
            {
                Id    = 0,
                Roles = new[] { "admin" },
                AllowedApplications = new[] { "content", "media", "members" },
                Culture             = "en-US",
                RealName            = "Admin",
                StartContentNodes   = new[] { -1 },
                StartMediaNodes     = new[] { -1 },
                Username            = "******"
            });

            UmbracoBackOfficeIdentity = identity;
        }
        public void Create_From_Claims_Identity_Required_Claim_Null()
        {
            var sessionId      = Guid.NewGuid().ToString();
            var claimsIdentity = new ClaimsIdentity(new[]
            {
                //null or empty
                new Claim(ClaimTypes.NameIdentifier, "", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.Name, "testing", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.GivenName, "hello world", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.StartContentNodeIdClaimType, "-1", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(Constants.Security.StartMediaNodeIdClaimType, "5543", ClaimValueTypes.Integer32, TestIssuer, TestIssuer),
                new Claim(Constants.Security.AllowedApplicationsClaimType, "content", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.AllowedApplicationsClaimType, "media", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(ClaimTypes.Locality, "en-us", ClaimValueTypes.String, TestIssuer, TestIssuer),
                new Claim(Constants.Security.SessionIdClaimType, sessionId, Constants.Security.SessionIdClaimType, TestIssuer, TestIssuer),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin", ClaimValueTypes.String, TestIssuer, TestIssuer),
            });

            Assert.Throws <InvalidOperationException>(() => UmbracoBackOfficeIdentity.FromClaimsIdentity(claimsIdentity));
        }
        public void Create_With_Forms_Ticket()
        {
            var sessionId = Guid.NewGuid().ToString();
            var userData  = new UserData(sessionId)
            {
                AllowedApplications = new[] { "content", "media" },
                Culture             = "en-us",
                Id              = 1234,
                RealName        = "hello world",
                Roles           = new[] { "admin" },
                StartMediaNodes = new [] { 654 },
                Username        = "******"
            };

            var ticket = new FormsAuthenticationTicket(1, userData.Username, DateTime.Now, DateTime.Now.AddDays(1), true,
                                                       JsonConvert.SerializeObject(userData));

            var identity = new UmbracoBackOfficeIdentity(ticket);

            Assert.AreEqual(12, identity.Claims.Count());
        }
예제 #20
0
        /// <summary>
        /// Unprotects the cookie
        /// </summary>
        /// <param name="protectedText"></param>
        /// <returns></returns>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            FormsAuthenticationTicket decrypt;

            try
            {
                decrypt = FormsAuthentication.Decrypt(protectedText);
                if (decrypt == null)
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            UmbracoBackOfficeIdentity identity;

            try
            {
                identity = new UmbracoBackOfficeIdentity(decrypt);
            }
            catch (Exception)
            {
                //if it cannot be created return null, will be due to serialization errors in user data most likely due to corrupt cookies or cookies
                //for previous versions of Umbraco
                return(null);
            }

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties
            {
                ExpiresUtc   = decrypt.Expiration.ToUniversalTime(),
                IssuedUtc    = decrypt.IssueDate.ToUniversalTime(),
                IsPersistent = decrypt.IsPersistent,
                AllowRefresh = true
            });

            return(ticket);
        }
        /// <summary>
        /// Unprotects the cookie
        /// </summary>
        /// <param name="protectedText"></param>
        /// <returns></returns>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            FormsAuthenticationTicket decrypt;

            try
            {
                decrypt = FormsAuthentication.Decrypt(protectedText);
                if (decrypt == null)
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            try
            {
                var identity = new UmbracoBackOfficeIdentity(decrypt);

                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties
                {
                    ExpiresUtc   = decrypt.Expiration.ToUniversalTime(),
                    IssuedUtc    = decrypt.IssueDate.ToUniversalTime(),
                    IsPersistent = decrypt.IsPersistent,
                    AllowRefresh = true
                });

                return(ticket);
            }
            catch (JsonReaderException)
            {
                //catch this and return null if the json is invalid
                //NOTE: This will happen when running on local host and developing on 7.6 and 7.7+ because 7.7 has a different
                // auth ticket format.
                return(null);
            }
        }
        /// <summary>
        /// Process an individual request.
        /// </summary>
        /// <param name="context"/>
        /// <returns/>
        public override async Task Invoke(IOwinContext context)
        {
            var request = context.Request;

            if (request.Uri.IsClientSideRequest() == false)
            {
                var claimsPrincipal = context.Request.User as ClaimsPrincipal;
                var isPreview       = request.HasPreviewCookie() &&
                                      claimsPrincipal != null &&
                                      request.Uri != null &&
                                      request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false;
                if (isPreview)
                {
                    //If we've gotten this far it means a preview cookie has been set and a front-end umbraco document request is executing.
                    // In this case, authentication will not have occurred for an Umbraco back office User, however we need to perform the authentication
                    // for the user here so that the preview capability can be authorized otherwise only the non-preview page will be rendered.

                    var cookie = request.Cookies[_cookieOptions.CookieName];
                    if (cookie.IsNullOrWhiteSpace() == false)
                    {
                        var unprotected = _cookieOptions.TicketDataFormat.Unprotect(cookie);
                        if (unprotected != null)
                        {
                            //Ok, we've got a real ticket, now we can add this ticket's identity to the current
                            // Principal, this means we'll have 2 identities assigned to the principal which we can
                            // use to authorize the preview and allow for a back office User.
                            claimsPrincipal.AddIdentity(UmbracoBackOfficeIdentity.FromClaimsIdentity(unprotected.Identity));
                        }
                    }
                }
            }

            if (Next != null)
            {
                await Next.Invoke(context);
            }
        }
예제 #23
0
        public override async Task Invoke(IOwinContext context)
        {
            IOwinRequest request = context.Request;

            if (request.Uri.AbsolutePath.StartsWith(MagicStrings.PreviewRouteBase) && request.Uri.Segments.Length == 6)
            {
                string[] segments = request.Uri.Segments;

                string userId = segments[3].Trim('/');
                IUser  user   = ApplicationContext.Current.Services.UserService.GetUserById(int.Parse(userId));

                UserData userData = GetUserData(user);

                Utility.ExpireCookie(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName);

                HttpCookie authCookie = CreateAuthCookie(
                    user.Name,
                    segments[2].Trim('/'),
                    JsonConvert.SerializeObject(userData),
                    UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName,
                    UmbracoConfig.For.UmbracoSettings().Security.AuthCookieDomain);

                HttpContext.Current.Request.Cookies.Add(authCookie);
                HttpContext.Current.Items.Add(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName, authCookie.Value);

                var identity = new UmbracoBackOfficeIdentity(userData);

                var securityHelper = new SecurityHelper(context);
                securityHelper.AddUserIdentity(identity);
            }

            if (Next != null)
            {
                await Next.Invoke(context);
            }
        }
예제 #24
0
 public AuthenticateEverythingAuthenticationOptions(UmbracoBackOfficeIdentity identity)
     : base("AuthenticateEverything")
 {
     AuthenticationMode        = AuthenticationMode.Active;
     UmbracoBackOfficeIdentity = identity;
 }