Trying to implement server to server authentication between my APIs through azure AD. First I am creating a token with following configuration
var oauthApi = RestService.For<IMidaApi>(
$"https://login.microsoftonline.com/{_settings.TenantId}",
new RefitSettings(new NewtonsoftJsonContentSerializer())
);
var data = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", _settings.ClientId},
{ "client_secret", _settings.SecretKey },
{ "scope", "api://1d1d113c-4b3b-****-******-********/.default" },
};
var response = await oauthApi.GetTokenAsync(data);
After successfully created token, Attaching to HTTPClient and doing request to another API which accepts Bearer token.
During validation it fails. I have added AzureAd section in appsettings with following values:
"AzureAd": {
"Instance": "https://sts.windows.net/",
"Audience": "api://1d1d113c-4b3b-4a2e-****-***********",
"ClientId": "1d1d113c-4b3b-4a2e-****-***********",
"TenantId": "3be67c15-c670-43c3-****-***********"
}
instance - after decoding jwt token i get the following for Issuer + tenant ID Audience exactly the same from decoded token Client and TenantId from AzureAd registered APP.
in startup provided this:
services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
app.UseAuthentication();
app.UseAuthorization();
is in correct order. Controller which needs this authentication has [Authorize] attribute.
Anything I do I keep getting Unauthorized exception.
Attaching some of the azure AD app registration configuration
seems like everything is correct here. Exposed API as following
And permissions:
What am I missing in this configuration?
Verified credentials.
I tried to reproduce the same in my environment and got the results as below:
I created an Azure AD Application and added scopes:
Now, I added API permissions as below:
I generated access token via Postman using Client Credentials like below:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:api://c0a52d3b-ec8a-4cce-a10e-d279axxxxxx/.default
grant_type:client_credentials
When I decoded the token, the scopes are not present in the access token:
Note that: For Client Credential Flow, you need to pass Application permissions. Delegated permissions are passed while generating access token via Authorization Code Flow.
To resolve the error, try the below:
I created App roles in the Azure AD Application:
Now, I added Application API permissions like below:
I generated access token via Postman using Client Credentials like below:
When I decoded the token, roles are present in the access token as below:
To resolve the error, try creating the App roles, grant Application API permissions and generate the token and check.