如何构建通用身份验证 Web API?

How do I build a generic authentication Web API?

我正在构建一个 Web API 应用程序,主要为纯 HTML + Angular UI 应用程序提供服务,但也为任何授权方提供服务。现在我主要希望 Web API,还有 UI 使用 'injected/configured' 身份验证服务。我想编写最少的代码并真正充分利用 ASP.NET 和 Identity 可以给我的东西。

实现此目标的既定和/或可接受的模型和做法是什么?

当然,应用程序所有者不能使用任何身份验证服务,它必须符合原型,可能实现接口,或使用某些自定义服务等,但我希望我的应用程序能够轻松置顶在最常见的场景之间切换,无论现在是什么场景。

请注意,这些只是最基本的设置。我强烈建议从已经配置身份的 File > New Project 开始。

Identity 在所有应用程序中实现起来都比较复杂,因为您需要应用程序的所有级别才能真正发挥作用(视觉、业务逻辑、数据库等)

如果您需要完整的解决方案,我会看一下 IdentityServer and its samples


在您的 Startup.cs/ConfigureServices 中确保包含以下部分:

// Configure our application database context to be Entity Framework backed by SQL Server
services.AddEntityFramework()
    .AddSqlServer()
    .AddDbContext(options =>
        options.UseSqlServer(Configuration.Get("Database:Connection")));

// Specify the configuration of our Application database context
services.Configure(options =>
{
    options.DefaultUsername = Configuration.Get("DefaultUser:Username");
    options.DefaultPassword = Configuration.Get("DefaultUSer:Password");
});

// Configure ASP.NET Identity to use our Identity-based application context
services.AddIdentity()
    .AddEntityFrameworkStores()
    .AddDefaultTokenProviders();

在你的 config.json 中需要这样的东西:

{
  "Mode": "Development",
  "Database": {
    "Connection": "Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "DefaultUser": {
    "Username": "myUsername",
    "Password": "MyP@ssword!"
  }
}

然后在你的 Startup.cs/Configure 我们实际上必须使用服务本身:

app.UseIdentity();

唯一缺少的是控制器上的 AuthorizeAttribute

首先,我想说安全很难。

第二件事,MVC 安全性通常基于cookie。 cookie 是通过本地登录页面或使用外部身份提供程序 (SSO) 获取的。如果它是从中央 SSO 提供程序获得的,那么您需要研究 WS-FederationOpenID Connect 等协议,或者您可以使用 社交媒体提供商 各种实施方式。

第三件事,Web API 安全性(这将是您从客户端 angular 代码保护的方式)将是 基于令牌。令牌将通过 OAuth 获得。这意味着您需要一个 OAuth 授权服务器。这可以在本地托管(就像您使用本地登录页面进行基于 cookie 的身份验证一样),也可以集中托管(就像您对外部 SSO 登录提供商一样)。

随着前端框架的发展以及当今我们构建 Web 应用程序的方式发生巨大变化,验证用户身份的首选方法是使用签名令牌作为随每个请求发送到服务器的令牌。使用这种方法的一些好处是:

  • 服务器的可扩展性
  • 松耦合
  • 移动友好

一个很好的教程和演示可以在 Token Based Authentication using ASP.NET Web API 2, Owin, and Identity

此外,请看一下 IdentityServer3 其中:

is a framework and a hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.