首页 > 解决方案 > CookieApplicationOptions LoginPath 何时何地检查重定向?

问题描述

具体来说,我的问题是关于 CookieApplicationOptions 和 LoginPath。我的项目成功使用 Aspnetcore.identity 登录并创建会话 cookie。

我的假设是,一旦我登录并创建 cookie,我将被重定向到我的 LoginPath,而在我登录并创建 cookie 之前,我将被定向到我的 AccessDeniedPath。这些都没有发生,所以我想知道何时调用这些被重定向。

目前在我的 Startup.cs 我有

public void ConfigureServices(IServiceCollection services)
        {

            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //Connect DB
            services.AddDbContext<DollaWebContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DollaWebContext")));

            //Create Table
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<DollaWebContext>()
                .AddDefaultTokenProviders();

            //Configure options for user
            services.Configure<IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequireLowercase = true;
                //options.Password.RequiredUniqueChars = 6;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers = false;

                // User settings
                options.User.RequireUniqueEmail = false;
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;



            });

           services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);

                options.LoginPath = new PathString("/register");
                options.LogoutPath = new PathString("/login");
                options.AccessDeniedPath = new PathString("/login");

                options.SlidingExpiration = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "$DollaApi", Version = "v1" });
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

从研究来看,这似乎与控制器中的 [Authorize] 标记有关,但大多数示例都没有给出具体原因。

标签: c#asp.net-mvcasp.net-coreasp.net-identity

解决方案


对于配置services.ConfigureApplicationCookie,它将在CookieAuthenticationHandler中使用。

对于身份验证过程,它是通过app.UseAuthorization();调用AuthorizationMiddleware来实现的。

    if (authorizeResult.Challenged)
    {
    if (policy.AuthenticationSchemes.Any())
    {
            foreach (var scheme in policy.AuthenticationSchemes)
            {
            await context.ChallengeAsync(scheme);
            }
    }
    else
    {
            await context.ChallengeAsync();
    }

    return;
    }
    else if (authorizeResult.Forbidden)
    {
    if (policy.AuthenticationSchemes.Any())
    {
            foreach (var scheme in policy.AuthenticationSchemes)
            {
            await context.ForbidAsync(scheme);
            }
    }
    else
    {
            await context.ForbidAsync();
    }

    return;
    }

对于context.ChallengeAsync(scheme);,它将调用AuthenticationService

    public virtual async Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)
    {
        if (scheme == null)
        {
            var defaultChallengeScheme = await Schemes.GetDefaultChallengeSchemeAsync();
            scheme = defaultChallengeScheme?.Name;
            if (scheme == null)
            {
                throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).");
            }
        }

        var handler = await Handlers.GetHandlerAsync(context, scheme);
        if (handler == null)
        {
            throw await CreateMissingHandlerException(scheme);
        }

        await handler.ChallengeAsync(properties);
    }

上面的代码将调用CookieAuthenticationHandler.


推荐阅读