且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择webApi模板后,如何将ASP.Net身份添加到Asp.Net Core?

更新时间:2023-02-15 08:32:42

这将为您提供具有aspnet核心标识的Bearapi Webapi,首先创建您的项目(假定您已经创建了一个新文件夹,并且位于其中):

This will give you a bear bones webapi with aspnet core identity, first create your project (this assumes you've created a new folder and you're in it):

dotnet new webapi

添加aspnet核心身份:

Add aspnet core identity:

dotnet add package Microsoft.AspNetCore.Identity

添加一些数据库提供程序来存储您的数据:

Add some database provider to store your data:

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

现在添加用户类型,最简单的版本是:

Now add a user type, the simplest version being:

public class ApplicationUser : IdentityUser
{
}

还有一个数据库上下文,这里我在类中设置连接字符串,但您可能想使用DbContextOptions代替:

And a db context, here I'm setting up the connection string within the class but you'd probably want to use DbContextOptions instead:

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
    protected override void OnConfiguring
        (DbContextOptionsBuilder optionsBuilder) => 
            optionsBuilder.UseSqlite("your connection string");
}

然后在Startup.cs中添加以下标记的行:

Then in your Startup.cs add the following marked lines:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;

    //add this: simply creates db if it doesn't exist, no migrations
    using (var context = new IdentityContext())
    {
        context.Database.EnsureCreated();
    }
}

public void ConfigureServices(IServiceCollection services)
{
    //add this: register your db context
    services.AddDbContext<IdentityContext>();

    //and this: add identity and create the db
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<IdentityContext>();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //add this
    app.UseAuthentication();

    app.UseMvc();
}

请注意,默认情况下,AddIdentity扩展名将设置默认的身份验证方案,并添加您可能不希望在API中使用的各种cookie,其替代方法如下(用于替换ConfigureServices中的上述AddIdentity调用):

Note that by default the AddIdentity extension will set the default authentication scheme and add various cookies that you probably don't want in an API, the cut down alternative is as follows (to replace the above AddIdentity call in ConfigureServices):

services.AddIdentityCore<ApplicationUser>(options => { });
new IdentityBuilder(typeof(ApplicationUser), typeof(IdentityRole), services)
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddSignInManager<SignInManager<ApplicationUser>>()
    .AddEntityFrameworkStores<IdentityContext>();

这将为您提供数据库方面的帮助,然后您可以使用UserManager和SignInManager创建和验证用户,以使他们使用DI系统:

This will give you the database side of things, you can then use UserManager and SignInManager to create and authenticate users, to get them use the DI system:

public class MyController : Controller
{
    private UserManager<ApplicationUser> _userManager = null;
    private SignInManager<ApplicationUser> _signInManager = null;

    public MyController(
        UserManager<ApplicationUser> userManager, 
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    //etc...

然后使用如下:

var result = await _userManager.CreateAsync(
    new ApplicationUser()
    {
        UserName = "bob", 
        Email = "bob@bob.com"
    }, "Test123!");
if (result.Succeeded)
    //do stuff...

并且:

var user = await _userManager.FindByNameAsync("bob");
result = await _signInManager.CheckPasswordSignInAsync(user, "Test123!", false);
if (result.Succeeded)
    //do stuff...

如果使用AddIdentity,则使用CheckPasswordSignInAsync代替PasswordSignInAsync将避免创建cookie,如果在上面也使用了AddIdentityCore,则必须使用CheckPasswordSignInAsync,因为PasswordSignInAsync将无法正常工作IAuthenticationSignInHandler尚未设置.

Using CheckPasswordSignInAsync instead of PasswordSignInAsync will avoid the creation of a cookie if AddIdentity is used, if AddIdentityCore was also used above, then you must use CheckPasswordSignInAsync as PasswordSignInAsync will not work as an IAuthenticationSignInHandler will not have been setup.