簡體   English   中英

選擇 webApi 模板時如何將 ASP.Net 身份添加到 Asp.Net Core?

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

我創建了一個 .NET Core 項目,選擇的 WebApi 模板不包括身份驗證。 我想在其中添加 ASP.NET 身份以進行基於角色的授權。 我怎樣才能做到這一點?

"

編輯:

這回答了這個問題,但總的來說,我同意對上述問題的評論 - JWT 不記名令牌最適合 API,最好在為您的用例決定最佳方法之前了解該選項。

原答案

這將為您提供一個帶有 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 調用):

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

如果使用了AddIdentity ,則使用CheckPasswordSignInAsync而不是PasswordSignInAsync將避免創建 cookie,如果AddIdentityCore還使用了AddIdentityCore ,那么您必須使用CheckPasswordSignInAsync因為PasswordSignInAsync將不起作用,因為IAuthenticationSignInHandler將不會被設置。

模板沒有什么特別的,你只需要 Microsoft.AspNet.Identity.Core NuGet 包,你應該可以從這里遵循:

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

我知道這個最初的帖子有多老,但它與我目前面臨的問題非常相關。 希望這是對我正在嘗試做的事情的簡單解釋。 目前,我將 ASP.NET Core Identity 用於 Web 應用程序,並且已經構建了一些 WebAPI,這些 WebAPI 將為 Web 應用程序提供數據。 想要將身份驗證和授權集中在一台服務器上,WebAPI 可以使用相同的身份驗證和授權數據庫來提供訪問權限。 現在,我認為必須有一種更簡單的方法來為此使用 3rd 方提供商。 我嘗試使用相同的 DBContext 為每個項目使用相同的身份配置,但失敗了。 我不明白為什么不能這么容易地實現。 據我了解,所有內容都存儲在數據庫中,所以我缺少什么。 謝謝你的幫助。 保重,度過美好的一天。

"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM