简体   繁体   English

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

[英]How to add ASP.Net identity to Asp.Net Core when webApi template is selected?

I have created a .NET Core project with WebApi template selected includes no authentication.我创建了一个 .NET Core 项目,选择的 WebApi 模板不包括身份验证。 I want to add ASP.NET identity in it for role based authorization.我想在其中添加 ASP.NET 身份以进行基于角色的授权。 How can I achieve this?我怎样才能做到这一点?

"

Edit:编辑:

This answers the question but generally speaking I agree with the comment on the question above - JWT bearer tokens are the best fit for an API, it's best to understand that option before deciding on the best approach for your use case.这回答了这个问题,但总的来说,我同意对上述问题的评论 - JWT 不记名令牌最适合 API,最好在为您的用例决定最佳方法之前了解该选项。

Original Answer原答案

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

dotnet new webapi

Add aspnet core identity:添加aspnet核心身份:

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
{
}

And a db context, here I'm setting up the connection string within the class but you'd probably want to use DbContextOptions instead:还有一个 db 上下文,我在这里设置了类中的连接字符串,但您可能想改用 DbContextOptions:

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

Then in your Startup.cs add the following marked lines:然后在您的 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();
}

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):请注意,默认情况下,AddIdentity 扩展将设置默认身份验证方案并添加您可能不希望在 API 中使用的各种 cookie,减少的替代方法如下(替换上述 ConfigureServices 中的 AddIdentity 调用):

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

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:这将为您提供数据库方面的信息,然后您可以使用 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...

And then use as follows:然后使用如下:

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

And:和:

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

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.如果使用了AddIdentity ,则使用CheckPasswordSignInAsync而不是PasswordSignInAsync将避免创建 cookie,如果AddIdentityCore还使用了AddIdentityCore ,那么您必须使用CheckPasswordSignInAsync因为PasswordSignInAsync将不起作用,因为IAuthenticationSignInHandler将不会被设置。

There is nothing special the template is doing, all you need is the Microsoft.AspNet.Identity.Core NuGet package and the you should be able to follow from here:模板没有什么特别的,你只需要 Microsoft.AspNet.Identity.Core NuGet 包,你应该可以从这里遵循:

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

I am aware of how old this initial post is, but it is very relevant to what problem I am facing currently.我知道这个最初的帖子有多老,但它与我目前面临的问题非常相关。 Hopefully, this is a simple explanation of what I am trying to do.希望这是对我正在尝试做的事情的简单解释。 Currently using ASP.NET Core Identity for a Web Application I have and have built out some WebAPI's that will supply data to Web Application.目前,我将 ASP.NET Core Identity 用于 Web 应用程序,并且已经构建了一些 WebAPI,这些 WebAPI 将为 Web 应用程序提供数据。 Want to centralize Authentication and Authorization on one server and WebAPI's can use same Authentication and Authorization database to provide access.想要将身份验证和授权集中在一台服务器上,WebAPI 可以使用相同的身份验证和授权数据库来提供访问权限。 Now, I figured there had to be an easier way that using a 3rd Party Provider for this.现在,我认为必须有一种更简单的方法来为此使用 3rd 方提供商。 I have attempted using the same Identity Configuration for each project using the same DBContext and that failed.我尝试使用相同的 DBContext 为每个项目使用相同的身份配置,但失败了。 I can't get why this can't be implemented this easily.我不明白为什么不能这么容易地实现。 Everything is stored in the database as I understand, so what am I missing.据我了解,所有内容都存储在数据库中,所以我缺少什么。 Thanks for your help.谢谢你的帮助。 Take Care and Have a Great day.保重,度过美好的一天。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM