【问题标题】:How to add ASP.Net identity to Asp.Net Core when webApi template is selected?选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?
【发布时间】:2017-08-30 15:41:51
【问题描述】:

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

【问题讨论】:

  • Identity 不太适合 Web API。改为查看 JwtBearer。

标签: c# asp.net-core asp.net-web-api asp.net-identity


【解决方案1】:

编辑:

这回答了问题,但总的来说,我同意对上述问题的评论 - 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,那么您必须使用CheckPasswordSignInAsync,因为PasswordSignInAsync 将不起作用IAuthenticationSignInHandler 不会被设置。

【讨论】:

  • 很好的答案。现在我们如何在每次必须调用 API 上的后续方法时检查用户是否已登录?我们应该使用 signinmanager.IsSignedIn 方法吗?
  • 很好的答案,但请记住,如果您遵循此答案并向服务添加带有 dbcontext 的选项,代码将会中断
【解决方案2】:

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

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

【讨论】:

  • 本文档解释了 Identity.Core 在您拥有 WebApp 而不是 WebApi 的情况下的使用
  • “WebApi”和“WebApp”之间没有区别了。文档是准确的。请参阅之前的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 2014-11-28
  • 2018-05-30
  • 1970-01-01
  • 2017-03-05
  • 2022-06-13
  • 2017-01-04
相关资源
最近更新 更多