[英]How set up Ocelot Api Gateway with Azure Active Directory
I followed this tutorial and managed to use api with Azure Active Directory authentication & authorization.我遵循本教程并设法将 api 与 Azure Active Directory 身份验证和授权结合使用。
However I would like to consume the api from behind the Ocelot Api Gateway.但是我想从 Ocelot Api Gateway 后面使用 api。 I could use ocelot with custom basic authorization but could not accomplish to use with Azure Active Directory.
我可以将 ocelot 与自定义基本授权一起使用,但无法与 Azure Active Directory 一起使用。
I have added Ocelot api gateway url to my api redirect url list already.我已经将 Ocelot api 网关 url 添加到我的 api 重定向 url 列表中。
How should I set ReRoutes values in config.json and Ocelot Api Gateway project StartUp.cs ?我应该如何在 config.json 和 Ocelot Api Gateway 项目 StartUp.cs 中设置 ReRoutes 值?
Any help will be appreciated.任何帮助将不胜感激。
Eventually I could.最终我可以。 First of all thanks to ocelot library because it supports Azure Active Directory authorization.
首先感谢ocelot 库,因为它支持Azure Active Directory 授权。
I assume that you can already completed this tutorial.我假设您已经可以完成本教程。
1-Create an ocelot api gateway project as usual. 1-照常创建ocelot api网关项目。
2-Add Microsoft.Identity.Web class library to ocelot project as reference 2-将Microsoft.Identity.Web类库添加到ocelot项目中作为参考
3-Add ocelot.json and it should be like below 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-Edit CreateWebHostBuilder method in Program.cs so that ocelot.json is used as additional config source. 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-Edit ConfigureServices and Configure methods in Startup.cs like below 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-Last but not least you should add your AzureAd configuration to ocelot api gateway project. 6-最后但并非最不重要的是,您应该将 AzureAd 配置添加到 ocelot api 网关项目。 (It should be same as ToDoListService for reference tutorial) Her you can see an example appsettings.json .
(参考教程应该与 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": "*"
}
I hope this answer save someones time and make their life happier :)我希望这个答案可以节省某人的时间并使他们的生活更快乐:)
Happy coding!快乐编码!
I was unable to get this working with the "Microsoft.Identity.Web" library.我无法使用“Microsoft.Identity.Web”库来实现这一点。 I received a host of errors such as:
我收到了许多错误,例如:
AuthenticationScheme: AzureADCookie was not authenticated... AuthenticationScheme:AzureADCookie 未通过身份验证...
-- and -- - 和 -
Signature validation failed...签名验证失败...
Instead, I managed to get the Azure B2C token validation, as well as the scopes, working as follows:相反,我设法获得了 Azure B2C 令牌验证以及范围,其工作方式如下:
1) ConfigureServices method (Startup.cs): 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 configuration (appsettings.json): 3)Azure AD B2C 配置(appsettings.json):
"AzureAdB2C": {
"Instance": "https://yourdomain.b2clogin.com",
"TenantId": "{tenantId}",
"SignUpSignInPolicyId": "your_signin_policy",
"ClientId": "{clientId}"
}
Hope this helps!希望这可以帮助! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.