首页 > 解决方案 > Asp.Net Core 2.2 身份认证

问题描述

我在我的网络应用程序中遇到了一个奇怪的情况,我可以成功登录但未通过身份验证。我检查了属性: User.Identity.IsAuthenticated 属性,其值为 false。我正在使用默认帐户控制器

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);

我设置了一个断点,结果的值为 Success,但 User.Identity.IsAuthenticated 为 false。

下面是我在 Startup 类中的 ConfigureServices 方法的代码:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SchoolIdentityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

        services.AddIdentity<User, IdentityRole>()
            .AddEntityFrameworkStores<SchoolIdentityContext>()
            .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            options.LoginPath = "/Account/Signin";
            options.LogoutPath = "/Account/Signout";
            options.AccessDeniedPath = "/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
        services.AddScoped<IBookCategoryService, BookCategoryService>();
        services.AddScoped<IBookService, BookService>();

        services.AddHttpClient("chikoroapi", c => 
        {
            c.BaseAddress = new Uri("http://localhost:5100/api");
        });

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

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

            // User settings.
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
            options.User.RequireUniqueEmail = true;
        });

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

        _services = services;
    }

配置方法如下

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            ListAllRegisteredServices(app);
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

我已经多次与文档进行交叉检查,但我无法弄清楚我遗漏了什么。

标签: c#authenticationasp.net-coreasp.net-identity

解决方案


SignIn 为将来的请求保留给定的信息,它不会在当前请求上设置 HttpContext.User。

您只能User.Identity.IsAuthenticated在登录时获得后续请求。

参考https://github.com/aspnet/Security/issues/1318


推荐阅读