Reputation: 58
I'm struggling with authentication in Web Api project that use OData. I thought that configuring authentication like this:
services.AddODataAuthorization((options) =>
{
options.ConfigureAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration.GetSection(Constants.AzureAd));
});
will be enough to enable authentication on all requests to OData endpoints. But no matter if token is passed, valid or invalid - api methods are always executed. HTTP 401 (unauthorized) is never returned.
In one of the examples there is an explicit use of HasReadRestrictions
method:
customers.HasReadRestrictions()
.HasPermissions(p => p.HasSchemeName("Scheme").HasScopes(s => s.HasScope("Customers.Read")))
.HasReadByKeyRestrictions(r => r.HasPermissions(p =>
p.HasSchemeName("Scheme").HasScopes(s => s.HasScope("Customers.ReadByKey"))));
Is it mandatory to configure all OData entities like that?
Upvotes: 1
Views: 1809
Reputation: 4233
From my understanding currently you have to specify [Authorize]
attribute for all controllers including OData because they're not anyhow different from others. ODataController is derived from ControllerBase.
This is kind of weird because you have to specify the same things twice.
Scheme permissions will be exposed in $metadata
endpoint but are not applied automatically.
There's an authorization library that solves this thing adding a middleware. But it's in beta stage since 2020 and available only for OData < 8.x.
Now if you need to copy policies in EDM is questionable. For example I need it to be exposed in OpenAPI specification. Up to you to decide if you need them.
Upvotes: 1