1

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?

3
  • 1
    Are you using the [Authorize] attribute on your controllers or methods? Commented Mar 11, 2021 at 10:49
  • 1
    @JHBonarius yes. In that project I have normal api controllers on which authorization works well. Only OData controllers pass unauthenticated requests. Commented Mar 11, 2021 at 11:04
  • Is there some useful info here? Commented Mar 11, 2021 at 11:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.