首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何利用Azure Active Directory建立Ocelot Api网关

如何利用Azure Active Directory建立Ocelot Api网关
EN

Stack Overflow用户
提问于 2019-05-06 11:57:46
回答 2查看 3.5K关注 0票数 2

我遵循了教程,并设法在Azure Active身份验证和授权中使用了api。

不过,我想从Ocelot网关后面使用api。我可以使用ocelot与自定义基本授权,但无法完成与Azure Active使用。

我已经将Ocelot网关url添加到我的api重定向url列表中。

如何在ReRoutes和Ocelot网关项目StartUp.cs中设置StartUp.cs值?

任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-07 12:57:00

最终我可以。首先,感谢ocelot库,因为它支持Azure Active授权。

我假设您已经可以完成教程了。

1-像往常一样创建ocelot网关项目。

2-向ocelot项目添加Microsoft.Identity.Web类库作为参考。

添加ocelot.json,它应该如下所示

代码语言:javascript
复制
    {
  "ReRoutes": [

    {
      "DownstreamPathTemplate": "/api/{catchAll}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 44351
        }
      ],
      "UpstreamPathTemplate": "/to-do-service/api/{catchAll}",

      "AuthenticationOptions": {
        "AuthenticationProviderKey": "AzureADJwtBearer",
        "AllowedScopes": []
      }
    }

  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:7070",
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}    

4-在CreateWebHostBuilder中编辑Program.cs方法,以便使用ocelot.json作为附加配置源.

代码语言:javascript
复制
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 config.AddJsonFile("ocelot.json", false, false);
             })
                .UseStartup<Startup>();

5-在ConfigureServices中编辑Startup.cs和配置方法,如下所示

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
        {
            services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration); //this extension comes from Microsoft.Identity.Web class library

            services.AddOcelot(Configuration);
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            await app.UseOcelot();
        }

最后但同样重要的是,您应该将您的AzureAd配置添加到ocelot网关项目中。(参考教程应该与ToDoListService相同)您可以看到一个示例appsettings.json。

代码语言:javascript
复制
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "client-id-guid-from-azure-ad",

    /*
      You need specify the TenantId only if you want to accept access tokens from a single tenant (line of business app)
      Otherwise you can leave them set to common
    */
    "Domain": "blablabla.onmicrosoft.com", // for instance contoso.onmicrosoft.com. Not used in the ASP.NET core template
    "TenantId": "tenant-id-guid-from-azure-ad" // A guid (Tenant ID = Directory ID) or 'common' or 'organizations' or 'consumers'
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"

}

我希望这个答案能节省一些时间,让他们的生活更快乐:)

编码愉快!

票数 5
EN

Stack Overflow用户

发布于 2020-03-18 15:29:31

我无法在"Microsoft.Identity.Web“库中完成这个任务。我收到了许多错误,例如:

AuthenticationScheme: AzureADCookie没有被认证..。

-而且--

签名验证失败..。

相反,我设法获得Azure B2C令牌验证以及作用域,如下所示:

1) ConfigureServices方法(Startup.cs):

代码语言:javascript
复制
    services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 
             })
           .AddJwtBearer(jwtOptions =>
           {
               jwtOptions.Authority = $"{Configuration["AzureAdB2C:Instance"]}/tfp/{Configuration["AzureAdB2C:TenantId"]}/{Configuration["AzureAdB2C:SignUpSignInPolicyId"]}";
               jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
               jwtOptions.TokenValidationParameters.ValidateIssuer = true; 
               jwtOptions.TokenValidationParameters.ValidIssuer = $"{Configuration["AzureAdB2C:Instance"]}/{Configuration["AzureAdB2C:TenantId"]}/v2.0/"; 
           }); 

            // Map scp to scope claims instead of http://schemas.microsoft.com/identity/claims/scope to allow ocelot to read/verify them
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("scp");
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Add("scp", "scope");


2) Ocelot re-routing configuration:

     {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "master-api",
          "Port": 5000
        }
      ],
      "UpstreamPathTemplate": "/master-api/{everything}",
      "UpstreamHttpMethod": [ "POST", "PUT", "GET", "DELETE" ],
      "ReRoutesCaseSensitive": false,
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": [ "master" ]
      }
    }

3) Azure AD B2C配置(appsettings.json):

代码语言:javascript
复制
  "AzureAdB2C": {
    "Instance": "https://yourdomain.b2clogin.com",
    "TenantId": "{tenantId}",
    "SignUpSignInPolicyId": "your_signin_policy",
    "ClientId": "{clientId}"
  }

希望这会有帮助!)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56004750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档