public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user        = new PocoUser("test");
            var httpContext = new Mock <HttpContext>();

            await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/ true, async() =>
            {
                var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
                id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                var principal  = new ClaimsPrincipal(id);
                var properties = new AuthenticationProperties {
                    IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1), IsPersistent = isPersistent
                };
                var ticket = new AuthenticationTicket(principal,
                                                      properties,
                                                      IdentityConstants.ApplicationScheme);

                var context = new CookieValidatePrincipalContext(httpContext.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
                {
                    HandlerType = typeof(NoopHandler)
                }.Build(), new CookieAuthenticationOptions(), ticket);
                Assert.NotNull(context.Properties);
                Assert.NotNull(context.Options);
                Assert.NotNull(context.Principal);
                await SecurityStampValidator.ValidatePrincipalAsync(context);
                Assert.NotNull(context.Principal);
            });
        }
        public static async Task ValidatePrincipalAsync(CookieValidatePrincipalContext context)
        {
            var tenant = context.HttpContext.GetTenant <SiteContext>();

            if (tenant == null)
            {
                context.RejectPrincipal();
            }

            var siteGuidClaim = new Claim("SiteGuid", tenant.Id.ToString());

            if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value))
            {
                var optionsAccessor = context.HttpContext.RequestServices.GetRequiredService <IOptions <MultiTenantOptions> >();
                var options         = optionsAccessor.Value;
                if (options.UseRelatedSitesMode == true)
                {
                    await SecurityStampValidator.ValidatePrincipalAsync(context);

                    return;
                }

                var logger = context.HttpContext.RequestServices.GetRequiredService <ILogger <SiteAuthCookieValidator> >();
                logger.LogInformation("rejecting principal because it does not have siteguid");
                context.RejectPrincipal();
            }
            else
            {
                await SecurityStampValidator.ValidatePrincipalAsync(context);
            }
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user            = new TestUser("test");
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var options = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });
            var httpContext     = new Mock <HttpContext>();
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
            var principal = new ClaimsPrincipal(id);

            var properties = new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1), IsPersistent = isPersistent
            };
            var signInManager = new Mock <SignInManager <TestUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();
            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(options.Object, signInManager.Object, new SystemClock()));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());

            var ticket = new AuthenticationTicket(principal,
                                                  properties,
                                                  IdentityConstants.ApplicationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
            {
                HandlerType = typeof(NoopHandler)
            }.Build(), new CookieAuthenticationOptions(), ticket);

            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
            SecurityStampValidator.ValidatePrincipalAsync(context);

            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
        public async Task OnValidatePrincipalThrowsWithEmptyServiceCollection()
        {
            var scheme      = new IdentityOptions().Cookies.ApplicationCookieAuthenticationScheme;
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(c => c.RequestServices).Returns(new ServiceCollection().BuildServiceProvider());
            var id     = new ClaimsPrincipal(new ClaimsIdentity(scheme));
            var ticket = new AuthenticationTicket(id, new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow
            }, scheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            var ex      = await Assert.ThrowsAsync <InvalidOperationException>(() => SecurityStampValidator.ValidatePrincipalAsync(context));
        }
        public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
        {
            var user            = new TestUser("test");
            var httpContext     = new Mock <HttpContext>();
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var identityOptions = new Mock <IOptions <IdentityOptions> >();

            identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
            var claimsManager = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            var options       = new Mock <IOptions <SecurityStampValidatorOptions> >();

            options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.FromDays(1)
            });
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <TestUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock <IAuthenticationSchemeProvider>().Object);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).Throws(new Exception("Shouldn't be called"));
            signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called"));
            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(options.Object, signInManager.Object, new SystemClock()));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow
            },
                                                  IdentityConstants.ApplicationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
            {
                HandlerType = typeof(NoopHandler)
            }.Build(), new CookieAuthenticationOptions(), ticket);

            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await SecurityStampValidator.ValidatePrincipalAsync(context);

            Assert.NotNull(context.Principal);
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user            = new TestUser("test");
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            var identityOptions = new IdentityOptions {
                SecurityStampValidationInterval = TimeSpan.Zero
            };
            var options = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext     = new Mock <HttpContext>();
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var properties = new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent
            };
            var signInManager = new Mock <SignInManager <TestUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, options.Object, null);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, properties, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();

            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance <ISecurityStampValidator>(new SecurityStampValidator <TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  properties,
                                                  IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());

            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
            SecurityStampValidator.ValidatePrincipalAsync(context);

            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
        public virtual async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            var            userName = context.Principal.GetUserName();
            DateTimeOffset?orig     = context.Properties.IssuedUtc;

            userName = userName?.Normalize().ToUpperInvariant();

            if (userName != null &&
                _cache.CheckExpired(userName, context.Properties.IssuedUtc))
            {
                context.Properties.IssuedUtc = null;
            }

            await SecurityStampValidator.ValidatePrincipalAsync(context);

            context.Properties.IssuedUtc = orig;
        }
        public async Task OnValidateIdentityRejectsWhenNoIssuedUtc()
        {
            var user            = new TestUser("test");
            var httpContext     = new Mock <HttpContext>();
            var userManager     = MockHelpers.MockUserManager <TestUser>();
            var claimsManager   = new Mock <IUserClaimsPrincipalFactory <TestUser> >();
            var identityOptions = new IdentityOptions {
                SecurityStampValidationInterval = TimeSpan.Zero
            };
            var options = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Value).Returns(identityOptions);
            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock <SignInManager <TestUser> >(userManager.Object,
                                                                     contextAccessor.Object, claimsManager.Object, options.Object, null);

            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(signInManager.Object);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(options.Object, signInManager.Object));
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  new AuthenticationProperties(),
                                                  identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());

            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await SecurityStampValidator.ValidatePrincipalAsync(context);

            Assert.Null(context.Principal);
            signInManager.VerifyAll();
        }
        public static IServiceCollection AddPlatoAuthentication(this IServiceCollection services)
        {
            // Configure antiForgery options
            services.TryAddEnumerable(ServiceDescriptor
                                      .Transient <IConfigureOptions <AntiforgeryOptions>, AntiForgeryOptionsConfiguration>());

            // Configure authentication services
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme       = IdentityConstants.ApplicationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                       options => { options.LoginPath = new PathString("/login"); })
            .AddCookie(IdentityConstants.ApplicationScheme, options =>
            {
                options.LoginPath = new PathString("/login");
                options.Events    = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async context =>
                    {
                        await SecurityStampValidator.ValidatePrincipalAsync(context);
                    }
                };
            })
            .AddCookie(IdentityConstants.ExternalScheme, options =>
            {
                options.Cookie.Name    = IdentityConstants.ExternalScheme;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme,
                       options => { options.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme; })
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, IdentityConstants.TwoFactorUserIdScheme, options =>
            {
                options.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });

            return(services);
        }
        private static async Task ValidatePrincipalImpl(CookieValidatePrincipalContext context)
        {
            var um = context.HttpContext.RequestServices
                     .GetRequiredService <UserManager>();
            var            userName = um.GetUserName(context.Principal);
            DateTimeOffset?orig     = context.Properties.IssuedUtc;

            if (userName != null)
            {
                userName = um.NormalizeName(userName);
                if (SlideExpireMemoryCache.TryGetValue("SlideExpiration: " + userName, out DateTimeOffset last) &&
                    last > context.Properties.IssuedUtc)
                {
                    context.Properties.IssuedUtc = null;
                }
            }

            await SecurityStampValidator.ValidatePrincipalAsync(context);

            context.Properties.IssuedUtc = orig;
        }
Example #11
0
        public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            var tenant = context.HttpContext.GetTenant <SiteContext>();

            if (tenant == null)
            {
                context.RejectPrincipal();
            }

            var siteGuidClaim = new Claim("SiteGuid", tenant.Id.ToString());

            if (_multiTenantOptions.UseRelatedSitesMode || context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value))
            {
                await SecurityStampValidator.ValidatePrincipalAsync(context);

                return;
            }
            else
            {
                _log.LogInformation("rejecting principal because it does not have siteguid");
                context.RejectPrincipal();
            }
        }
Example #12
0
    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        if (!(cache.Get <bool?>($"renewPuckClaims{context.Principal.Identity.Name}") ?? false))
        {
            await SecurityStampValidator.ValidatePrincipalAsync(context);

            return;
        }

        cache.Remove($"renewPuckClaims{context.Principal.Identity.Name}");

        var claims = context.Principal.FindAll(Claims.PuckStartId)?.ToList();

        if (claims != null && claims.Any())
        {
            for (var i = 0; i < claims.Count; i++)
            {
                ((ClaimsIdentity)context.Principal.Identity).RemoveClaim(claims[i]);
            }
        }

        var user = await userManager.FindByNameAsync(context.Principal.Identity.Name);

        if (user != null && !string.IsNullOrEmpty(user.PuckStartNodeIds))
        {
            var ids      = user.PuckStartNodeIds.Split(',', System.StringSplitOptions.RemoveEmptyEntries).Select(x => Guid.Parse(x));
            var validIds = repo.GetPuckRevision().Where(x => ids.Contains(x.Id) && x.Current).Select(x => x.Id).Distinct().ToList();
            foreach (var startNodeId in validIds)
            {
                ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim(Claims.PuckStartId, startNodeId.ToString()));
            }
        }
        context.ReplacePrincipal(context.Principal);
        context.ShouldRenew = true;

        await SecurityStampValidator.ValidatePrincipalAsync(context);
    }
Example #13
0
        public static void AddSecurity(this IServiceCollection services)
        {
            // Adds the default token providers used to generate tokens for reset passwords, change email
            // and change telephone number operations, and for two factor authentication token generation.
            new IdentityBuilder(typeof(User), typeof(Role), services).AddDefaultTokenProviders();

            // 'IAuthenticationSchemeProvider' is already registered at the host level.
            // We need to register it again so it is taken into account at the tenant level.
            services.AddSingleton <IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                o.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                o.DefaultSignInScheme       = IdentityConstants.ExternalScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.Events    = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async context =>
                    {
                        await SecurityStampValidator.ValidatePrincipalAsync(context);
                    }
                };
            })
            .AddCookie(IdentityConstants.ExternalScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
                       o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme)

            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });

            // Identity services
            services.TryAddScoped <IUserValidator <User>, UserValidator <User> >();
            services.TryAddScoped <IPasswordValidator <User>, PasswordValidator <User> >();
            services.TryAddScoped <IPasswordHasher <User>, PasswordHasher <User> >();
            services.TryAddSingleton <ILookupNormalizer, UpperInvariantLookupNormalizer>();

            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAddScoped <IdentityErrorDescriber>();
            services.TryAddScoped <ISecurityStampValidator, SecurityStampValidator <User> >();
            services.TryAddScoped <IUserClaimsPrincipalFactory <User>, UserClaimsPrincipalFactory <User, Role> >();
            services.TryAddScoped <UserManager <User> >();
            services.TryAddScoped <SignInManager <User> >();

            services.TryAddScoped <IUserStore <User>, UserStore>();

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IMembershipService, MembershipService>();
            services.AddScoped <IRoleRemovedEventHandler, UserRoleRemovedEventHandler>();

            services.TryAddScoped <RoleManager <Role> >();
            services.TryAddScoped <IRoleStore <Role>, RoleStore>();
            services.TryAddScoped <IRoleProvider, RoleStore>();
            services.TryAddScoped <IRoleClaimStore <Role>, RoleStore>();

            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddScoped <IAuthorizationHandler, RolesPermissionsHandler>();
        }
Example #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddAuthentication().AddCookie(o =>
            {
                o.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = context =>
                    {
                        return(SecurityStampValidator.ValidatePrincipalAsync(context));
                    },
                    OnRedirectToAccessDenied = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                        return(Task.FromResult(0));
                    },
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                        return(Task.FromResult(0));
                    }
                };
            });

            services.AddIdentity <ApplicationUser, IdentityRole>(o =>
            {
                o.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromHours(1);
                o.Lockout.MaxFailedAccessAttempts = 3;
                o.Lockout.AllowedForNewUsers      = true;
            }).AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders();

            services.AddMvc(options =>
            {
                options.Filters.AddService(typeof(AngularAntiforgeryCookieResultFilter));
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });

            services.Configure <SecurityStampValidatorOptions>(o =>
            {
                o.ValidationInterval = TimeSpan.Zero;
            });

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-Token");

            services.AddTransient <IEmailSender, EmailSender>(sp => new EmailSender(
                                                                  Configuration["Tracktor:SmtpHost"],
                                                                  Int32.Parse(Configuration["Tracktor:SmtpPort"]),
                                                                  Boolean.Parse(Configuration["Tracktor:SmtpSsl"]),
                                                                  Configuration["Tracktor:SmtpSender"],
                                                                  Configuration["Tracktor:SmtpUsername"],
                                                                  Configuration["Tracktor:SmtpPassword"]));

            services.AddSingleton(CreateServiceClient());

            services.AddSingleton(Configuration);

            services.AddTransient <AngularAntiforgeryCookieResultFilter>();
        }
        public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
        {
            var user = new TestUser {
                UserName = "******"
            };

            var manager = SetupUserManager(user);

            manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
            manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable();

            var context = new Mock <HttpContext>();

            var contextAccessor = new Mock <IHttpContextAccessor>();

            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);

            var roleManager = MockHelpers.MockRoleManager <TestRole>();

            var options = new Mock <IOptions <IdentityOptions> >();

            options.Setup(a => a.Value).Returns(new IdentityOptions());

            var securityStampOptions = new Mock <IOptions <SecurityStampValidatorOptions> >();

            securityStampOptions.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions {
                ValidationInterval = TimeSpan.Zero
            });

            var claimsFactory = new UserClaimsPrincipalFactory <TestUser, TestRole>(manager.Object, roleManager.Object, options.Object);
            var logStore      = new StringBuilder();
            var loggerFactory = new MockLoggerFactory();
            var logger        = loggerFactory.CreateLogger <SignInManager <TestUser> >();

            var helper     = new Mock <SignInManager <TestUser> >(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger, new Mock <IAuthenticationSchemeProvider>().Object, new Mock <IUserConfirmation <TestUser> >().Object);
            var properties = new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1)
            };

            var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);

            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
            var principal = new ClaimsPrincipal(id);

            //because the request fails the create user principal is never called and therefore not verifiable
            //helper.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();
            //helper.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(user).Verifiable();
            //helper.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(default(TestUser)).Verifiable();
            helper.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called"));

            var services = new ServiceCollection();

            services.AddSingleton(options.Object);
            services.AddSingleton(helper.Object);
            services.AddSingleton <ILoggerFactory>(loggerFactory);
            services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(securityStampOptions.Object, helper.Object, new SystemClock()));

            context.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id),
                                                  new AuthenticationProperties {
                IssuedUtc = DateTimeOffset.UtcNow
            },
                                                  IdentityConstants.ApplicationScheme);

            var cookieContext = new CookieValidatePrincipalContext(context.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme)
            {
                HandlerType = typeof(NoopHandler)
            }.Build(), new CookieAuthenticationOptions(), ticket);

            Assert.NotNull(cookieContext.Properties);
            Assert.NotNull(cookieContext.Options);
            Assert.NotNull(cookieContext.Principal);
            await SecurityStampValidator.ValidatePrincipalAsync(cookieContext);

            Assert.NotNull(cookieContext.Principal);
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ServiceInjection.Register(new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            });
            services.AddServiceInjection();
            var connStr = Configuration.GetConnectionString("DataContext");

#if TEST
            connStr = connStr.Replace("{envConfig}", ".Test");
#else
            connStr = connStr.Replace("{envConfig}", "");
#endif
            services.AddDbContext <DataContext>(options =>
            {
                options.UseSqlServer(connStr);
            });
            Data.Global.Init(services);
            Business.Global.Init(services);
            #region OAuth
            //for some default Identity configuration
            services.AddIdentity <AppUser, AppRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;
            })
            .AddEntityFrameworkStores <DataContext>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });
            #endregion
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly  = true;
                options.AccessDeniedPath = Routing.ACCESS_DENIED;
                options.ExpireTimeSpan   = TimeSpan.FromHours(
                    WebAdmin.Settings.Instance.CookiePersistentHours);
                options.LoginPath                  = Routing.LOGIN;
                options.LogoutPath                 = Routing.LOGOUT;
                options.ReturnUrlParameter         = "return_url";
                options.SlidingExpiration          = true;
                options.Events.OnValidatePrincipal = async(c) =>
                {
                    var identity = c.Principal.Identity as ClaimsIdentity;
                    //extra claims will be expired after amount of time
                    if (identity.FindFirst(AppClaimType.UserName)?.Value == null)
                    {
                        var identityService = c.HttpContext.RequestServices.GetRequiredService <IdentityService>();
                        var entity          = await identityService.GetUserByUserNameAsync(identity.Name);
                        var extraClaims     = identityService.GetExtraClaims(entity);
                        identity.AddClaims(extraClaims);
                        c.ShouldRenew = true;
                    }
                    await SecurityStampValidator.ValidatePrincipalAsync(c);
                };
            });
            services.AddControllers();
            services.AddRazorPages(options =>
            {
                var allowAnnonymousPages = new[] {
                    "/AccessDenied", "/Error", "/Status", "/Identity/Login",
#if DEBUG
                    "/Identity/Register"
#endif
                };
                var authorizeFolders         = new[] { "/" };
                var authorizeLocationFolders = new[] { "/" };
                options.Conventions
                .AddAreaPageRoute("Location", "/Dashboard/Index", Routing.LOCATION_DASHBOARD)
                .AddAreaPageRoute("Location", "/Resource/Index", Routing.LOCATION_RESOURCE)
                .AddAreaPageRoute("Location", "/Resource/Create", Routing.LOCATION_RESOURCE_CREATE)
                .AddAreaPageRoute("Location", "/Post/Index", Routing.LOCATION_POST)
                .AddAreaPageRoute("Location", "/Post/Detail", Routing.LOCATION_POST_DETAIL)
                .AddAreaPageRoute("Location", "/Post/Create", Routing.LOCATION_POST_CREATE)
                .AddAreaPageRoute("Location", "/Building/Index", Routing.LOCATION_BUILDING)
                .AddAreaPageRoute("Location", "/Building/Create", Routing.LOCATION_BUILDING_CREATE)
                .AddAreaPageRoute("Location", "/Floor/Index", Routing.LOCATION_FLOOR)
                .AddAreaPageRoute("Location", "/Floor/Create", Routing.LOCATION_FLOOR_CREATE)
                .AddAreaPageRoute("Location", "/Floor/Detail", Routing.LOCATION_FLOOR_DETAIL)
                .AddAreaPageRoute("Location", "/Area/Index", Routing.LOCATION_AREA)
                .AddAreaPageRoute("Location", "/Area/Create", Routing.LOCATION_AREA_CREATE)
                .AddAreaPageRoute("Location", "/Device/Index", Routing.LOCATION_DEVICE)
                .AddAreaPageRoute("Location", "/Config/Index", Routing.LOCATION_CONFIG)
                .AddAreaPageRoute("Location", "/Config/Create", Routing.LOCATION_CONFIG_CREATE)
                .AddAreaPageRoute("Location", "/Config/Detail", Routing.LOCATION_CONFIG_DETAIL)
                .AddAreaPageRoute("Location", "/Config/ScreenSaver", Routing.LOCATION_CONFIG_SSP)
                .AddAreaPageRoute("Location", "/Config/Overview", Routing.LOCATION_CONFIG_OVERVIEW)
                .AddAreaPageRoute("Location", "/Config/Contact", Routing.LOCATION_CONFIG_CONTACT)
                .AddAreaPageRoute("Location", "/Schedule/Index", Routing.LOCATION_SCHEDULE)
                .AddAreaPageRoute("Location", "/Schedule/Create", Routing.LOCATION_SCHEDULE_CREATE)
                .AddAreaPageRoute("Location", "/Schedule/Detail", Routing.LOCATION_SCHEDULE_DETAIL)
                .AddAreaPageRoute("Location", "/Schedule/ScheduleDetail", Routing.LOCATION_S_DETAIL_DETAIL)
                .AddPageRoute("/Post/Detail", Routing.POST_DETAIL)
                .AddPageRoute("/ResType/Detail", Routing.RES_TYPE_DETAIL)
                .AddPageRoute("/EtCate/Detail", Routing.ENTITY_CATE_DETAIL)
                .AddPageRoute("/Owner/Detail", Routing.OWNER_DETAIL);
                foreach (var f in authorizeFolders)
                {
                    options.Conventions.AuthorizeFolder(f);
                }
                foreach (var f in authorizeLocationFolders)
                {
                    options.Conventions.AuthorizeAreaFolder("Location", f);
                }
                foreach (var p in allowAnnonymousPages)
                {
                    options.Conventions.AllowAnonymousToPage(p);
                }
            });
        }
Example #17
0
        // ISecurityStampValidator
        // ISecurityStampValidator
        // ISecurityStampValidator

        public Task ValidateAsync(CookieValidatePrincipalContext context)
        {
            return(SecurityStampValidator.ValidatePrincipalAsync(context));
        }
Example #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ServiceInjection.Register(new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            });
            services.AddServiceInjection();
            var connStr = Configuration.GetConnectionString("DataContext");

#if TEST
            connStr = connStr.Replace("{envConfig}", ".Test");
#else
            connStr = connStr.Replace("{envConfig}", "");
#endif
            services.AddDbContext <DataContext>(options =>
            {
                options.UseSqlServer(connStr);
            });
            Data.Global.Init(services);
            Business.Global.Init(services);
            #region OAuth
            //for some default Identity configuration, include AddAuthentication (IdentityConstants)
            services.AddIdentity <AppUser, AppRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;
            })
            .AddEntityFrameworkStores <DataContext>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });
            #endregion
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly  = true;
                options.AccessDeniedPath = Constants.Routing.ACCESS_DENIED;
                options.ExpireTimeSpan   = TimeSpan.FromHours(
                    WebAdmin.Settings.Instance.CookiePersistentHours);
                options.LoginPath                  = Constants.Routing.LOGIN;
                options.LogoutPath                 = Constants.Routing.LOGOUT;
                options.ReturnUrlParameter         = "return_url";
                options.SlidingExpiration          = true;
                options.Events.OnValidatePrincipal = async(c) =>
                {
                    var identity = c.Principal.Identity as ClaimsIdentity;
                    //extra claims will be expired after amount of time
                    if (identity.FindFirst(Business.Constants.AppClaimType.UserName)?.Value == null)
                    {
                        var identityService = c.HttpContext.RequestServices.GetRequiredService <IIdentityService>();
                        var entity          = await identityService.GetUserByUserNameAsync(identity.Name);
                        var extraClaims     = identityService.GetExtraClaims(entity);
                        identity.AddClaims(extraClaims);
                        c.ShouldRenew = true;
                    }
                    await SecurityStampValidator.ValidatePrincipalAsync(c);
                };
            });
            services.AddScoped <Layout>();
            services.AddControllers();
            services.AddRazorPages(options =>
            {
                var allowAnnonymousPages = new[] {
                    "/AccessDenied", "/Error", "/Status", "/Identity/Login", "/Identity/Register"
                };
                var authorizeFolders = new[] { "/" };
                options.Conventions
                .AddPageRoute("/Resource/Detail", Constants.Routing.RESOURCE_DETAIL)
                .AddPageRoute("/ProductionLine/Detail", Constants.Routing.PRODUCTION_LINE_DETAIL)
                .AddPageRoute("/ProductModel/Detail", Constants.Routing.PRODUCT_MODEL_DETAIL)
                .AddPageRoute("/QCDevice/Detail", Constants.Routing.QC_DEVICE_DETAIL)
                .AddPageRoute("/ProductionBatch/Detail", Constants.Routing.PRODUCTION_BATCH_DETAIL)
                .AddPageRoute("/QCEvent/Detail", Constants.Routing.QC_EVENT_DETAIL)
                .AddPageRoute("/AppConfig/Detail", Constants.Routing.APP_CONFIG_DETAIL)
                .AddPageRoute("/DefectType/Detail", Constants.Routing.DEFECT_TYPE_DETAIL);
                foreach (var f in authorizeFolders)
                {
                    options.Conventions.AuthorizeFolder(f);
                }
                foreach (var p in allowAnnonymousPages)
                {
                    options.Conventions.AllowAnonymousToPage(p);
                }
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(Settings.Instance.FirebaseCredentials),
            });
            ServiceInjection.Register(new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            });
            services.AddServiceInjection();
            var connStr = Configuration.GetConnectionString("DataContext");

#if TEST
            connStr = connStr.Replace("{envConfig}", ".Test");
#else
            connStr = connStr.Replace("{envConfig}", "");
#endif
            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(connStr).UseLazyLoadingProxies());
            Data.Global.Init(services);
            var fapSecret = File.ReadAllText(Settings.Instance.FapSecretFile);
            Business.Global.Init(services, fapSecret);
            #region OAuth
            services.AddIdentity <AppUser, AppRole>(options =>
            {
                options.SignIn.RequireConfirmedEmail = false;
            })
            .AddEntityFrameworkStores <DataContext>();
            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });
            //required
            services.AddAuthentication()
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = JWT.ISSUER,
                    ValidAudience    = JWT.AUDIENCE,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.Default.GetBytes(JWT.SECRET_KEY)),
                    ClockSkew = TimeSpan.Zero
                };
                //jwtBearerOptions.Events = new JwtBearerEvents
                //{
                //    OnMessageReceived = (context) =>
                //    {
                //        return Task.CompletedTask;
                //        //StringValues values;
                //        //if (!context.Request.Query.TryGetValue("access_token", out values))
                //        //    return Task.CompletedTask;
                //        //var token = values.FirstOrDefault();
                //        //context.Token = token;
                //        //return Task.CompletedTask;
                //    }
                //};
            });
            #endregion
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly  = true;
                options.AccessDeniedPath = Routing.ACCESS_DENIED;
                options.ExpireTimeSpan   = TimeSpan.FromHours(
                    WebAdmin.Settings.Instance.CookiePersistentHours);
                options.LoginPath                  = Routing.LOGIN;
                options.LogoutPath                 = Routing.LOGOUT;
                options.ReturnUrlParameter         = "return_url";
                options.SlidingExpiration          = true;
                options.Events.OnValidatePrincipal = async(c) =>
                {
                    var identity = c.Principal.Identity as ClaimsIdentity;
                    //extra claims will be expired after amount of time
                    if (identity.FindFirst(AppClaimType.UserName)?.Value == null)
                    {
                        var identityService = c.HttpContext.RequestServices.GetRequiredService <IdentityService>();
                        var entity          = await identityService.GetUserByUserNameAsync(identity.Name);
                        var principal       = await identityService.GetApplicationPrincipalAsync(entity);
                        c.ReplacePrincipal(principal);
                        c.ShouldRenew = true;
                    }
                    await SecurityStampValidator.ValidatePrincipalAsync(c);
                };
            });
            services.AddScoped <Layout>();

            services.AddSingleton(new DefaultDateTimeModelBinder());
            services.AddControllers(options =>
            {
                options.ModelBinderProviders.Insert(0, new QueryObjectModelBinderProvider());
            }).AddNewtonsoftJson();
            services.AddRazorPages(options =>
            {
                var allowAnnonymousPages = new[] {
                    "/AccessDenied", "/Error", "/Status", "/Identity/Login", "/Identity/Register"
                };
                var authorizeFolders = new[] { "/" };
                foreach (var f in authorizeFolders)
                {
                    options.Conventions.AuthorizeFolder(f);
                }
                foreach (var p in allowAnnonymousPages)
                {
                    options.Conventions.AllowAnonymousToPage(p);
                }
            });
        }
Example #20
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddSecurity();

            // Adds the default token providers used to generate tokens for reset passwords, change email
            // and change telephone number operations, and for two factor authentication token generation.
            new IdentityBuilder(typeof(IUser), typeof(IRole), services).AddDefaultTokenProviders();

            // 'IAuthenticationSchemeProvider' is already registered at the host level.
            // We need to register it again so it is taken into account at the tenant level.
            services.AddSingleton <IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                o.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                o.DefaultSignInScheme       = IdentityConstants.ExternalScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, o =>
            {
                o.LoginPath = new PathString("/Account/Login");
                o.Events    = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = async context =>
                    {
                        await SecurityStampValidator.ValidatePrincipalAsync(context);
                    }
                };
            })
            .AddCookie(IdentityConstants.ExternalScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
                       o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme)

            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });

            // Identity services
            services.TryAddScoped <IUserValidator <IUser>, UserValidator <IUser> >();
            services.TryAddScoped <IPasswordValidator <IUser>, PasswordValidator <IUser> >();
            services.TryAddScoped <IPasswordHasher <IUser>, PasswordHasher <IUser> >();
            services.TryAddSingleton <ILookupNormalizer, UpperInvariantLookupNormalizer>();

            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAddScoped <IdentityErrorDescriber>();
            services.TryAddScoped <ISecurityStampValidator, SecurityStampValidator <IUser> >();
            services.TryAddScoped <IUserClaimsPrincipalFactory <IUser>, UserClaimsPrincipalFactory <IUser, IRole> >();
            services.TryAddScoped <UserManager <IUser> >();
            services.TryAddScoped <SignInManager <IUser> >();

            services.TryAddScoped <IUserStore <IUser>, UserStore>();

            services.ConfigureApplicationCookie(o =>
            {
                o.Cookie.Name      = "orchauth_" + _tenantName;
                o.Cookie.Path      = new PathString(_tenantPrefix);
                o.LoginPath        = new PathString("/" + LoginPath);
                o.AccessDeniedPath = new PathString("/" + LoginPath);
                // Using a different DataProtectionProvider per tenant ensures cookie isolation between tenants
                o.DataProtectionProvider = _dataProtectionProvider;
            })
            .ConfigureExternalCookie(o =>
            {
                o.DataProtectionProvider = _dataProtectionProvider;
            })
            .Configure <CookieAuthenticationOptions>(IdentityConstants.TwoFactorRememberMeScheme, o =>
            {
                o.DataProtectionProvider = _dataProtectionProvider;
            })
            .Configure <CookieAuthenticationOptions>(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.DataProtectionProvider = _dataProtectionProvider;
            });

            services.AddSingleton <IIndexProvider, UserIndexProvider>();
            services.AddSingleton <IIndexProvider, UserByRoleNameIndexProvider>();
            services.AddScoped <IDataMigration, Migrations>();

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IMembershipService, MembershipService>();
            services.AddScoped <ISetupEventHandler, SetupEventHandler>();
            services.AddScoped <ICommandHandler, UserCommands>();
            services.AddScoped <IRoleRemovedEventHandler, UserRoleRemovedEventHandler>();

            services.AddScoped <IPermissionProvider, Permissions>();
            services.AddScoped <INavigationProvider, AdminMenu>();

            services.AddScoped <ILiquidTemplateEventHandler, UserLiquidTemplateEventHandler>();

            services.AddScoped <IDisplayManager <User>, DisplayManager <User> >();
            services.AddScoped <IDisplayDriver <User>, UserDisplayDriver>();
            services.AddScoped <IDisplayDriver <User>, UserButtonsDisplayDriver>();
        }