I’m currently working on a .NET Core project where I’m using Ocelot as an API Gateway and I want to use Auth0 for handling permissions and scopes. I have already set up Ocelot in ASP.Net Core and Auth0 in my frontend project, and I have defined the necessary routes and scopes as well. In my Auth0 account I have some users along with roles and scopes setup.
I send a request to the backend while logged in and passing the accesstoken as a Bearer
header. Although the network-tab gives a 401 unauthorized
, not sure if I’m missing anything since I’m pretty new to ocelot/auth0 and the docs weren’t too clear to me.
I have a user in Auth0 which has a role assigned to it with the read:posts scope active.
Here is the current version of my ocelot.json file:
{
"Routes": [
{
"UpstreamPathTemplate": "/api/posts",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamHostAndPorts": [ { "Host": "post-service", "Port": 8081 } ],
"DownstreamPathTemplate": "/api/posts",
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer",
"AllowedScopes": ["read:posts"]
}
},
{
"UpstreamPathTemplate": "/api/posts/{id}",
"UpstreamHttpMethod": [ "Get" ],
"DownstreamHostAndPorts": [ { "Host": "post-service", "Port": 8081 } ],
"DownstreamPathTemplate": "/api/posts/{id}"
}
]
}
And here is how I have configured Auth0 in my appsettings.json file:
{
"Auth0": {
"Domain": "dev-[DOMAIN].us.auth0.com",
"Audience": "https://[HOST].com/api"
}
}
Parts of my Program.cs
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
// Configure Authentication
builder.Services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = $"https://{builder.Configuration["Auth0:Domain"]}/";
options.Audience = builder.Configuration["Auth0:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
builder.Services.AddOcelot(builder.Configuration);
app.UseOcelot().Wait();
Any help or guidance would be greatly appreciated.