首页 > 解决方案 > Azure AD 和 Aspnet Core Identity 如何协同工作?

问题描述

我目前正在建立一个项目,其中 Vue.Js 作为我的前端,Aspnet Core 作为我的后端。我之前使用过这两种技术,但我以前从未使用过 Azure AD。我的 Vue.js 应用程序可以从 Azure AD 获取访问令牌,并且我已将其作为不记名令牌附加,但我不太明白如何使用该令牌在映射的数据库(EF Core)中创建用户身份?假设我有一个需要 userId 的模型

public class Post
{
     public string UserId {get; set;}
     //Other fields
}

我知道令牌包含声明,我可以使用该声明来识别用户,但由于我的数据库是空的,它是如何工作的?

启动.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlite("Data Source=test.db");
            });
        services.AddIdentity<IdentityUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 4;
            })
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration);
        // Some other stuff
        services.AddControllers();
    }

appsettings.json 看起来像这样

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "<something>.onmicrosoft.com",
  "TenantId": "<something>",
  "ClientId": "<something>",
  "CookieSchemeName": "Identity.External"
},

标签: c#apivue.jsasp.net-coreazure-active-directory

解决方案


为了实现这个场景,它有两个部分:

  1. Web App 代表已登录用户调用 Web API。要实现这一点,您必须配置客户端应用程序以调用 Web API。在此之后,将帮助您为您的 Web API 提供 Web 应用委派权限。

  2. 您不必检查用户的 SQL db,您可以 Azure AD 在内部为您执行此操作,您只需使用以下代码:

    public void ConfigureServices(IServiceCollection services)
    {
        // Adds Microsoft Identity platform (AAD v2.0) support to protect this API
        services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
    
        services.AddControllers();
    }
    

    有关代码配置的更多详细信息,请访问受保护的 Web API:代码配置

  3. ASP.NET 核心标识:

    • 是一种支持用户界面 (UI) 登录功能的 API。
    • 管理用户、密码、配置文件数据、角色、声明、令牌、电子邮件确认等。

    Microsoft 身份平台是:

    • Azure Active Directory (Azure AD) 开发人员平台的演变。
    • 与 ASP.NET Core 标识无关。

    ASP.NET Core Identity 向 ASP.NET Core Web 应用程序添加了用户界面 (UI) 登录功能。要保护 Web API 和 SPA,请使用以下方法之一:

    • Azure 活动目录
    • Azure Active Directory B2C (Azure AD B2C)
    • 身份服务器4

    对于不同的代码设置,请访问:ASP.NET Core 上的身份简介

您可能混合了两种不同的方法,请查看这些链接以进一步澄清。


推荐阅读