如何在选择webApi模板时向Asp.Net Core添加ASP.Net标识?

时间:2017-04-05 07:08:13

标签: c# asp.net asp.net-core

我创建了一个.NET Core项目,其中选择了WebApi模板,不包含任何身份验证。我想在其中添加ASP.NET标识以进行基于角色的授权。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:21)

这将为您提供带有aspnet核心身份的熊骨头webapi,首先创建您的项目(假设您创建了一个新文件夹并且您已经在其中):

dotnet new webapi

添加aspnet核心标识:

dotnet add package Microsoft.AspNetCore.Identity

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

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

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

public class ApplicationUser : IdentityUser
{
}

还有db上下文,这里我在类中设置连接字符串,但你可能想要使用DbContextOptions:

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

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

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调用): / p>

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

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

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...

使用CheckPasswordSignInAsync代替PasswordSignInAsync将避免在使用AddIdentity时创建Cookie,如果上面也使用AddIdentityCore,那么您必须使用{{1}由于CheckPasswordSignInAsync不会被设置,因此PasswordSignInAsync将无效。

答案 1 :(得分:0)

模板没有什么特别之处,你需要的只是Microsoft.AspNet.Identity.Core NuGet包,你应该可以从这里开始:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity