asp.net核心身份+ API

mar*_*c08 5 asp.net-mvc asp.net-web-api asp.net-core-mvc asp.net-core

我刚刚开始学习asp.net核心。我想创建一个简单的Web应用程序,在asp.net核心中有一个其余的API,然后在一个单独的前端中消耗一些API。

我只是在尝试弄清楚ASP.NET Core身份和cookie /令牌身份验证时有些困惑...

我的问题很简单:我是否可以创建一个API并使用实体框架进行数据库处理,并使用ASP.NET Core Identity来处理创建和管理用户及授权?我是否还必须使用一些JWT,OAuth或类似的东西?只是这对我来说是超级新手,我感到困惑,因为每个示例/教程都以不同的方式显示它,我感到非常困惑...

谢谢你的帮助!

cha*_*ger 2

我正在做一个非常相似的项目。查看 IdentityServer4 https://identityserver4.readthedocs.io/en/release/index.html它是一个用于 ASP.NET Core 的开源 OpenID Connect/OAuth 2 框架,由来自leastprivilege https://leastprivilege.com的人员创建。

您可以使用 JWT 来保护您的 API,并将 IdentityServer 配置为将 ASP.NET Core Identity 用于其用户存储。本节介绍了保护 API: https://identityserver4.readthedocs.io/en/release/configuration/apis.html

这基本上就是添加 ASP.NET Identity、IdentityServer 以及配置 IdentityServer 以在 Startup.cs 中使用 ASP.NET Identity 的方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

services.AddMvc();

// Adds IdentityServer
services.AddIdentityServer()
    .AddAspNetIdentity<ApplicationUser>();
}
Run Code Online (Sandbox Code Playgroud)

那么保护 API 只需要 Startup.cs 中的几行代码

public void Configure(IApplicationBuilder app)
{
    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "https://demo.identityserver.io",
        AllowedScopes = { "api1" },
    });

    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

然后,您必须将 Angular 应用程序配置为 IdentityServer 的“客户端”,并能够访问您的 API“资源”。有一个关于添加 JavaScript 客户端的完整教程:https://identityserver4.readthedocs.io/en/release/quickstarts/7_javascript_client.html