0
votes

I am trying to authenticate against a standard ASP.NET web application API using Azure AD authentication.

I am able to get a token from the Azure application using the clientId and secret, but when I try to create a GET request in powershell i get a 401 unauthorized.

Shouldn't the token for the application that was created with the web application grant access to the API?

This is the script used to produce the result.

$postParams = @{
    grant_type='client_credentials';
    client_id=$clientId;
    client_secret=$clientSecret;
    resource='https://graph.microsoft.com';
}

$token = Invoke-WebRequest -Uri "https://login.microsoftonline.com/$($tenantId)/oauth2/token" -Method 
Post -Body $postParams | select -expand content | convertfrom-json | select -expand access_token

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "bearer $token")

Invoke-WebRequest -Uri "https://localhost:32775/weatherforecast" -Method Get -Headers $headers -ContentType "application/json"

Which returns.

Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
1
Not sure, but I think bearer should be Bearer with a capital BTheo
Yeah, tried to change it without effect.Zucchini
Are you getting a $token back from the first request? If you are, try Base-64-decoding it with this function to see if the contents are as you expect.Rich Moss
I used jwt.io, it looks to contain the right information.Zucchini

1 Answers

0
votes

Please Specify what is in your postParams, I think you are probably missing a scope or resource. https://blog.tekspace.io/access-azure-rest-api-using-powershell/

Normally you would have 2 app registrations, one for the web api, and one for the client (in this case powershell). Technically you could have them both on the same app reg, but not usually best practice. https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi#register-the-service-app-todolist-webapi-daemon-v2 This is how you set up the app registration for applications, because you are using app secret, then its looking for a resource and your api permissions have to be application permissions and not delegated permissions. so you need to expose api, then add an approle to the manifest. then under api permissions of the client, you can add api permissions my api-> application-> approlename etc. you would then handle it in the code of your asp.net application

Your api also has to be set up to handle the role. because with a client credentials flow, its a roles claim and not a scope claim. https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#application-permissions