Reputation: 101
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
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:
register an app from Azure classic portal
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
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"
});
Get
method of TodoListController
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