首页 > 解决方案 > ASP.NET Core 身份验证失败

问题描述

我的 .NET Core 版本是:3.1,我想通过 验证我的用户Identity,这里是Startup.cs代码:

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wulikunkun.Web.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Identity;

namespace Wulikunkun.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
            services.AddHttpContextAccessor();
            services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(Environment.GetEnvironmentVariable("MySqlConnection")));
            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

            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 = 6;
                options.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;
                // User settings.
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/Home/Index";
                options.LogoutPath = "/Home/Index";
                options.AccessDeniedPath = "/Home/Index";
            });
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo { Title = "wulikunkun's api", Version = "v1" });
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

这是我的LogIn操作代码的一部分:

          var result = _signManager.PasswordSignInAsync(user.UserName, user.Password, true, true);
                if (result.IsCompletedSuccessfully)
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name,corrUser.UserName),
                        new Claim(ClaimTypes.Email,corrUser.Email)
                     };
                    await _userManager.AddClaimsAsync(corrUser, claims);
                }
                return Json(new
                {
                    StatusCode = 1
                });

但是我发现返回Http.Uesr.Identity.IsAuthenticated时是假的,这是我的文件内容:result.IsCompletedSuccessfullytruecsproj

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.8">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.21" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Ninject" Version="3.3.4" />
    <PackageReference Include="StackExchange.Redis" Version="2.1.58" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.7" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.7" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
    <PackageReference Include="NLog" Version="4.6.7" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Migrations" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Wulikunkun.Utility\Utility.csproj" />
  </ItemGroup>

  <ProjectExtensions>
    <VisualStudio>
      <UserProperties appsettings_1json__JsonSchema="" />
    </VisualStudio>
  </ProjectExtensions>

</Project>

标签: asp.netasp.net-core.net-core

解决方案


AddAuthentication需要注入ConfigureServices。否则不会触发认证服务。

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddAuthentication();
    //...
}

结果。

在此处输入图像描述

这是我的注册动作。

    [HttpPost]
    public async Task<IActionResult> Register(string username, string password)
    {
        var user = new IdentityUser
        {
            UserName = username,
            Email = "",
        };
        var result = await _userManager.CreateAsync(user, password);
        if (result.Succeeded)
        {
            var res = _signInManager.PasswordSignInAsync(username, password, true, true);
            return Json(new
            {
                StatusCode = 2
            }); //Carrry cookie to browser. 
        }
        return View("Index");
    }

推荐阅读