Getting access denied when accessing Azure Web App via token - azure

We are testing locking down an API hosted on Azure Web Apps by using the built-in Azure Web App Authentication/Authorization with Azure Active Directory.
We are calling POST https://login.microsoftonline.com/{tenantIDhere}/oauth2/v2.0/token with the following parameters in Postman:
grant_type: password
client_id: {ID}
username: {username}#{tenenat}.onmicrosoft.com
password: {password}
scope: https://{webappname}.azurewebsites.net/.default
client_secret: {secret}
Below is the response I get:
"token_type":"Bearer","scope":"https://{webappname}.azurewebsites.net/user_impersonation https://{webappname}.azurewebsites.net/.default","expires_in":3599,"ext_expires_in":3599,"access_token":"{TOKEN HERE}"}
So I take that token and try and access the webpage by passing the token in the header and I get the below error using POST:
https://{webappname}.azurewebsites.net/api/url
Authorization: Bearer {TOKEN HERE}
Response (401 Unauthorized)
You do not have permission to view this directory or page.
I have spent days trying everything I can find. What am I missing?? As soon as I turn off authorization needed for the web app, I get the expected result. But using the grant_type: password, I CANNOT get in! I have a feeling its related to the scope, but I cannot find documentation on what I need here for this. Any ideas?
The user is able to manually login to the webpage and pull the data, so it is not a permission issue. It has something to do with the token I believe.

If you are using v2.0 endpoint, the scope should be {your_client_id}/.default. Replace https://{webappname}.azurewebsites.net with the client id/application id for your API app in Azure AD.
Edit:
As Wayne said, you could also set scope as {your_client_id}/User.Read to get access token.

Related

Query Application Insights via Azure REST API

I'm trying to query application insights via their REST API. I'm stuck on getting a token.
I have created an API key using the API Access blade in Azure Application Insights:
That gives you an Application ID and an API Key.
I have populated postman with the following:
url: https://login.microsoftonline.com/<Our Tenant ID>/oauth2/token
tenant: <Our Tenant ID>
client_id: <The Application ID from the API Access screen>
scope: https://api.applicationinsights.io/.default
client_secret: <The API Key from the API Access screen>
grant_type: client_credentials
All of this is taken from their documentation page here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#get-a-token
The error is as follows:
"error": "unauthorized_client",
"error_description": "AADSTS700016: Application with identifier '<application ID from API Access screen>' was not found in the directory '<My Company Name>'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: 57f78a92-fe94-40e3-a183-e3002be32801\r\nCorrelation ID: 0ab8e3ec-655d-44aa-93fa-4d3941862d11\r\nTimestamp: 2022-11-30 15:04:20Z",
I checked with the Azure Admin for our company and I'm definitely sending this to the right tenant. Also he created another key for me so it's not that either.
Thanks.
I tried to reproduce the same in my environment and got below results:
I created an API key from API Access blade in Azure Application Insights like below:
When I tried to acquire the token via Postman with below parameters, I got same error as below:
POST https://login.microsoftonline.com/<TenantID>/oauth2/token
client_id: <Application ID from API Access screen>
grant_type:client_credentials
client_secret: <API Key from API Access screen>
scope: https://api.applicationinsights.io/.default
Response:
There is no need to generate token separately if you want to query Application insights using API key.
Without including token, you can directly query Application insights by including x-api-key header like below:
GET https://api.applicationinsights.io/v1/apps/{Application ID from API Access screen}/metadata
x-api-key: <API Key from API Access screen>
Response:
The process you are currently following works only if you want to authenticate your API via Azure AD. In that case, you can generate the access token by granting required roles and scopes to registered Azure AD application.
But if your requirement is using API key, you can run any query by simply including x-api-key header for Authorization purpose.

Replicate Postman Oauth 2.0 using Python

I have this Authorization request that works.
How can I replicate it in Python?
I am using an Azure AD to authenticate the access.
Since you are working with python, your case is a : Oauth2 login for SSR web applications with Microsoft
Goal
Get an access_token from interactive login using the oauth2 authorization code grant
Steps
Here I will list all the steps required to do it with any language
Create a web with session with at least these endpoints
/ : home page
/callback : server route or path able to receive query params like /callback?code=123456. This along with your base domain will be called redirect_uri. Sample : http://localhost:8080/callback or http://acme.com/callback
Create and configure an app in Azure Dev Console. Same process is in Google, Facebook, Linkedin, etc. As a result you should have a clientId, clientSecret and a redirect url
Create a simple web with classic session in which if user is not logged-in, redirect (302) to this url:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=foo&response_type=code&redirect_uri=foo&response_mode=query&scope=offline_access%20user.read%20mail.read
clientid and redirect_uri are important here and should be the same of previous step
After that, browser should redirect the user to the platform login
If user enters valid credentials and accepts the consent warning, Microsoft will perform another redirect (302) to the provided redirect_uri but with special value: The auth code
http://acme.com/callback?code=123456798
In the backend of /callback get the code and send it to this new endpoint
Add a client_id & client_secret parameters
Add a code parameter with the code sent by microsoft
Add a redirect_uri parameter with previously used and registered on azure. Sample http://acme.com/callback or http://localhost:8080/callback
Add a grant_type parameter with a value of authorization_code
Issue the HTTP POST request with content-type: application/x-www-form-urlencoded
You should get a response with the precious access_token:
{
token_type: 'Bearer',
scope: 'Mail.Read User.Read profile openid email',
expires_in: 5020,
ext_expires_in: 5020,
access_token: 'eyJ0oVlKhZHsvMhRydQ',
refresh_token: 's_Rcrqf6xMaWcPHJxRFwCQFkL_qUYqBLM71UN6'
}
You could do with this token, whatever you configured in azure. Sample: If you want to access to user calendar, profile, etc on behalf of the user, you should have registered this in the azure console. So the clientid is related to that and human user will be prompted with something like this
Libraries
There is some libraries provided by microsoft (c#, nodejs) which will save you a little work. Anyway the previous explanation are very detailed.
Advice
Read about oauth2 spec: https://oauth.net/2/
Read about oauth2 authorization code flow login before the implementation with python
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow
https://github.com/msusdev/microsoft_identity_platform_dev/blob/main/presentations/auth_users_msalnet.md
Check this to understand how configure the azure web console: https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
Check my gist https://gist.github.com/jrichardsz/5b8ba730978fce7a7c585007d3fd06b4

Azure B2C React SPA dose not providing access token

I am working on my first project of connecting Azure B2C with MERN App. I wanted to Sign In using Azure B2C and authorise my web API using the Access Token.
I configured everything and applied configurations to this sample React tutorial provide by their documentation.
The problem arises while calling the Web API. The Web API call are sending without any token. When I check the code, acquireTokenSilent function returning empty accessToken from response.
instance.acquireTokenSilent({
scopes: protectedResources.apiHello.scopes,
account: account
}).then(async (response) => {
console.log(response)
The Request is:
Even though I looked many forums and Microsoft technical forums, no answer is not working.
But what I noticed is, it is requesting for grant_type: authorization_code but am not seeing access token in the response. Posting here the API call, request and response.
The Response is producing id_token but not access token,
I gave grant permission in the SPA App permission for task.read scope. I tried everything but I am still receiving the access token as empty. How could I fix this issue?
I tried to reproduce the same in my environment and got below results:
I registered one Azure AD B2C application for app1 and added scopes(task.read) as below:
Now I created one SPA registration and added API permissions by granting consent like this:
I created Sign up and sign in policy and ran the user flow as below:
Please Check authentication and access token and id token:
I signed in as user it gave me auth code in address bar.
https://<tenant name >.b2clogin.com/<tenant name> .onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_susi&client_id=<app id>&nonce=defaultNonce&redirect_uri=https://jwt.ms&scope=openid%20https%3A%2F%2F<tenant name>.onmicrosoft.com tasks.read&response_type=code&prompt=login&code_challenge_method=S256&code_challenge=<challenge paramater>
I generated the access token via Postman with commands like this:
POST https://tenant.b2clogin.com/tenant.onmicrosoft.com/policy/oauth2/v2.0/token
grant_type: authorization_code
client_id: SPA_appid
scope: https://tenant.onmicrosoft.com/app1/task.read
redirect_uri: redirect_uri
code: code
code_verifier: code_verifier
Postman
When I decode the token i getting scp in jwt .ms

Azure Functions returns "401 Unauthorized" only with Postman

I have some troubles trying to call an Azure Function (code) with Postman.
I have already set up the Authentication / Authorization and settings.
It's working with my browser (with login page).
But when I try to use Postman, I'm getting 401 :
"You do not have permission to view this directory or page."
I also tried to use the Postman built-in (see configuration) Oauth2 to login. I can successfully get the tokens (access and refresh). But it seems that my API request to functions are not working...
Here is the final API Call: postman screenshot
The aad tenant_id starts with 8d6, the application client_id starts with 226, and the app secret ends with Av2.
Is there anything wrong ... ? It looks like actually, Azure Functions handle only Cookies for the authentication, that's why it's working with the browser and not Postman. How can I make it works with the header Authorization / Bearer ?
Thanks for your help !
The way you got the access token is not correct. Just like #Marc said, in your Postman you are not specifying a resource or scope. The postman get new access token tool only has the scope parameter, so you should use the v2.0 endpoint to get the access token.
Auth URL:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
Access Token URL:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Scope:
{clientId}/.default

JWT token issue on Azure Management API

I've been trying to use the Azure Service Management API in order to list the Hosted Services with no success.
In the first place, I was able to set up the authentication using PowerShell as the Microsoft documentation states here: https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
My first step was to request an access token using OAuth2 making a POST request to this URL:
https://login.windows.net/<MY_TENANT_ID>/oauth2/token
and passing these parameters:
grant_type: client_credentials
client_id: <THE_CLIENT_ID_OF_THE_APP_REGISTERED_THROUGH_POWERSHELL>
client_secret: <THE_PASSWORD_OF_APP_REGISTERED_THROUGH_POWERSHELL>
resource: https://management.core.windows.net
so, I receive a valid response and an access_token included in the response. So far so good.
Then, I want to make a simple call to the Management API; I would like to list my Hosted Services (Cloud Services), so I make a GET request to this URL:
https://management.core.windows.net/<MY_SUBSCRIPTION_ID>/services/hostedservices
Including the following headers:
Authorization: Bearer <THE_ACCESS_TOKEN_RECEIVED_IN_THE_PREVIOUS_STEP>
x-ms-version: 2014-10-01 (I've also tested with different versions)
but, what I get is a 401 Unauthorized error, with the following message:
The JWT token does not contain expected audience uri 'https://management.core.windows.net/'
I also tried with a Native Application registered directly in the Azure Portal (with Permissions set to use the Service Management API) and requesting a token using the grant_type = authorization_code. I get the access_token correctly and a refresh_token, but when I try to make a request to the above URL, I get the same error message.
On a side note, I am able to use the Azure Insights API successfully; the issue above is with the Azure Service Management API.
Anyone knows what I am missing?
I faced the same problem today. Complete the resource url with '/' https://management.core.windows.net
See the mismatch between the url in your resource and the one in the error message 'https://management.core.windows.net/'

Resources