Mr Perfect
Mr Perfect

Reputation: 685

Implement Azure AD authentication for Web API which can be called from multiple clients with and without user context?

Net core application and Single Page application. I have implemented Authorization code flow for authentication. In SPA users login and call the APIs. This is working as expected. so my WebAPI accepts requests coming from SPA and only authenticated requests such as tokens contains roles. Now I have requirement such that I should add one more controller to the same App which can accept requests from another client app. This client app do not have logged in user. So its kind of service to service call like client credential flow. Now I want to implement second flow. So ultimately my Web API can be called from SPA with authenticated users and from another app without authenticated users. I am trying to implement this and not sure this way its possible or not. The reason being is I have below code in web api

var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
        services.AddMvc(options =>
        {
            options.Filters.Add(typeof(ValidateModelStateAttribute));
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
        .AddNewtonsoftJson(options => {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        });

This says allow only authenticated users in the app. I generated token for my another client app as below

https://login.microsoftonline.com/tenantid/oauth2/v2.0/token

and passed client id, client secret grant_type and scope as api://clientid of webapi. I got token and tried to hit web API but this could not success. It throws error

System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.

I need some help regarding this, first is this possible in first then if possible what is the right way or any thing I am missing here. Can someone please help me. Any help would be appreciated. Thanks

Upvotes: 0

Views: 834

Answers (1)

juunas
juunas

Reputation: 58908

You need to go to your app registration in Azure AD management portal, find "App roles", and create an app role with allowed member types "Applications". This is an application permission.

Then you need to go the app registration for the client application and add that app permission under API permissions. You will need to then do admin consent to give the permission to the client application.

For integrations between systems where users are not involved, you should always define an application permission. You can have as much or as little granularity as you want, you can have a single app permission that allows access to all endpoints, or you can have permissions per entity type that you expose (similar to MS Graph API).

Upvotes: 1

Related Questions