Philipp Bauknecht
Philipp Bauknecht

Reputation: 101

Authenticate Native App with asp.net core Backend using Azure AD with Client Secret

I'm currently developing a Kiosk terminal where I need to grant access for a UWP app to a REST API built with asp.net core using Azure AD. Since there is no user as it is a kiosk setup I created a Azure AD app registration (web app) and also created a key to use as client secret.

I manage to get a Bearer Access Token using a POST request to https://login.microsoftonline.com/{myTenant}/oauth2/token providing the ClientId, ClientSecret and desired Resource (=AppId of my app registration).

In my asp.net core app I did enable JWTBearerAuthentication like this:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    Authority = Configuration["ClientAuthentication:AADInstance"] + Configuration["ClientAuthentication:TenantId"],
    Audience = Configuration["ClientAuthentication:Audience"]
});

and I use the Authorize attribute in my API controller.

In this setup I always get a

401 unauthorized

when calling this API using the Bearer token in the Authorization header.

Any ideas?

Upvotes: 4

Views: 1961

Answers (1)

Fei Xue
Fei Xue

Reputation: 14649

The code sample is only for checking the code issue because I am not able to reproduce this issue.

Here is my trying:

  1. register an app from Azure classic portal

  2. acquire the token using the client credentials flow like below:

//7f39bae4-f852-41ae-8a7b-54d022cf65bd is the client_id of app
POST:https://login.microsoftonline.com/{tenantId}/oauth2/token
grant_type=client_credentials&client_id=7f39bae4-f852-41ae-8a7b-54d022cf65bd&client_secret={clientSecret}&resource=7f39bae4-f852-41ae-8a7b-54d022cf65bd
  1. clone the code sample from here
  2. modify the Startup class as the code you provide

 app.UseJwtBearerAuthentication(new JwtBearerOptions {
            Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
            Audience = "7f39bae4-f852-41ae-8a7b-54d022cf65bd"
        });
  1. run the ToDoListService project
  2. set the breakpoint for the Get method of TodoListController
  3. send the request using Fiddler like below

GET:https://localhost:44321/api/TodoList
Authorization: bearer {accessToken}

The break point was hit well for me. Please ensure that the audience is the client id of your app. If you still have the issue, I suggest you follow the step above to check whether it helps.

Upvotes: 1

Related Questions