Где и когда CookieApplicationOptions LoginPath проверяет перенаправление? - PullRequest
0 голосов
/ 14 октября 2019

В частности, мой вопрос касается CookieApplicationOptions и LoginPath. Мой проект успешно использует Aspnetcore.identity для входа в систему и создания файла cookie сеанса.

Я предполагал, что я буду перенаправлен на свой LoginPath, как только я войду в систему и создаю cookie, и прежде чем я войду в систему и создаю 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] в контроллере, но большинство примеров не даютконкретная причина, почему.

1 Ответ

0 голосов
/ 14 октября 2019

Для настройки 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.

...