如何使用 Azure Active Directory 设置 Ocelot Api 网关
How set up Ocelot Api Gateway with Azure Active Directory
我遵循了 this 教程并设法将 api 与 Azure Active Directory 结合使用
身份验证和授权。
不过我想从 Ocelot Api 网关后面使用 api。
我可以使用具有自定义基本授权的 ocelot,但无法与 Azure Active Directory 一起使用。
我已经将 Ocelot api 网关 url 添加到我的 api 重定向 url 列表中。
我应该如何在 config.json 和 Ocelot Api 网关项目 StartUp.cs 中设置 ReRoutes 值?
任何帮助将不胜感激。
最终我可以。
首先感谢 ocelot 库,因为它支持 Azure Active Directory 授权。
我假设您已经完成了 this 教程。
1-像往常一样创建一个ocelot api网关项目。
2-将Microsoft.Identity.Web class库添加到ocelot项目作为参考
3-添加ocelot.json,它应该像下面的
{
"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-编辑 Program.cs 中的 CreateWebHostBuilder 方法,以便 ocelot.json 用作附加配置源。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("ocelot.json", false, false);
})
.UseStartup<Startup>();
5-编辑 Startup.cs 中的 ConfigureServices 和 Configure 方法,如下所示
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();
}
6-最后但同样重要的是,您应该将 AzureAd 配置添加到 ocelot api 网关项目。 (参考教程应该和ToDoListService一样)
她你可以看到一个例子 appsettings.json .
{
"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": "*"
}
我希望这个回答能节省一些人的时间,让他们的生活更快乐:)
编码愉快!
我无法在 "Microsoft.Identity.Web" 库中使用它。我收到了很多错误,例如:
AuthenticationScheme:AzureADCookie 未通过身份验证...
-- 和--
签名验证失败...
相反,我设法获得了 Azure B2C 令牌验证以及范围,工作如下:
1) ConfigureServices 方法 (Startup.cs):
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):
"AzureAdB2C": {
"Instance": "https://yourdomain.b2clogin.com",
"TenantId": "{tenantId}",
"SignUpSignInPolicyId": "your_signin_policy",
"ClientId": "{clientId}"
}
希望对您有所帮助! :)
我遵循了 this 教程并设法将 api 与 Azure Active Directory 结合使用 身份验证和授权。
不过我想从 Ocelot Api 网关后面使用 api。 我可以使用具有自定义基本授权的 ocelot,但无法与 Azure Active Directory 一起使用。
我已经将 Ocelot api 网关 url 添加到我的 api 重定向 url 列表中。
我应该如何在 config.json 和 Ocelot Api 网关项目 StartUp.cs 中设置 ReRoutes 值?
任何帮助将不胜感激。
最终我可以。 首先感谢 ocelot 库,因为它支持 Azure Active Directory 授权。
我假设您已经完成了 this 教程。
1-像往常一样创建一个ocelot api网关项目。
2-将Microsoft.Identity.Web class库添加到ocelot项目作为参考
3-添加ocelot.json,它应该像下面的
{
"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-编辑 Program.cs 中的 CreateWebHostBuilder 方法,以便 ocelot.json 用作附加配置源。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("ocelot.json", false, false);
})
.UseStartup<Startup>();
5-编辑 Startup.cs 中的 ConfigureServices 和 Configure 方法,如下所示
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();
}
6-最后但同样重要的是,您应该将 AzureAd 配置添加到 ocelot api 网关项目。 (参考教程应该和ToDoListService一样) 她你可以看到一个例子 appsettings.json .
{
"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": "*"
}
我希望这个回答能节省一些人的时间,让他们的生活更快乐:)
编码愉快!
我无法在 "Microsoft.Identity.Web" 库中使用它。我收到了很多错误,例如:
AuthenticationScheme:AzureADCookie 未通过身份验证...
-- 和--
签名验证失败...
相反,我设法获得了 Azure B2C 令牌验证以及范围,工作如下:
1) ConfigureServices 方法 (Startup.cs):
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):
"AzureAdB2C": {
"Instance": "https://yourdomain.b2clogin.com",
"TenantId": "{tenantId}",
"SignUpSignInPolicyId": "your_signin_policy",
"ClientId": "{clientId}"
}
希望对您有所帮助! :)