Can't access azure storage blob via url even though authenticated - node.js

I have a nodejs application using the express framework. The user must sign in via Oauth2 protocol against their MS Azure Active Directory credentials. This is done using the passport-azure-ad-oauth2 npm package
I have successfully got the application working so that I can upload files in blob form to an azure storage container. The container access level is set to private. I have assigned user roles for the container so that certain users within the AD have 'reader and data access'. So my understanding is that when these users are authenticated via Oauth2, they should be able to access the files when retrieving the file's URL. However, after authentication, I am not able to access the files. I get the following error.
ResourceNotFound
The specified resource does not exist. RequestId:6341ef80-f01e-0011-6442-08f7c2000000 Time:2021-02-21T11:14:26.3475641Z
I have also followed the steps to grant the application permissions to azure storage here
What do I need to do so that authenticated users can go to the specific url for each blob and get access? Do I need to pass a token in the request? If so, how do you do this?
Any help would be much appreciated.

The 404 error(The specified resource does not exist) is always related to your request URL, but not the access token.
For example to get blob, you need to use GET Method, and some of the Request Headers are required.
GET https://myaccount.blob.core.windows.net/mycontainer/myblob
headers:
Authorization: Bear <access-token>
x-ms-version: 2020-04-08
x-ms-date: Fri, 26 Jun 2015 23:39:12 GMT
Get access token by application permission without user:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
client_id={client_id}
&client_secret={client_secret}
&scope=http://storage.azure.com/.default // change to http://storage.azure.com/ for resource
&grant_type=client_credentials
Get access token by delegated permission with a signed-in user:
GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id={client_id}
&response_type=token
&redirect_uri=https://localhost:44300/
&scope=https://storage.azure.com/user_impersonation
&response_mode=fragment
&state=12345
&nonce=678910
Note: Navigate to your storage account -> Access Control (IAM) -> Add role assignment -> select Storage Blob Data XXX role and your login account. I add Storage Blob Data Contributor in my side, it might take up to 5 minutes to propagate the RBAC rule.

Related

rest operations Azure Datalake gen2

I want to do operations in Azure datalake gen2 using rest operations. I have a service principal with client secret and having owner access on storage account.
I am confused how to construct the request for operations. I can't find any proper example demonstrating it.
The way which I want is to:
Get access token
Make a put request with bearer authentication method
Below are documents which I am referring
Access token
Put blob operation
I want to do it through postman. It would be really helpful if someone can suggest it
I tried to reproduce the same in my environment and got below results:
I created one service principal named DataLake and added API permissions as below:
Now, I granted Storage Blob Data Contributor role to that service principal at storage account level like below:
Go to Azure Portal -> Storage Accounts -> Your storage account -> Access Control (IAM) -> Add role assignment -> Storage Blob Data Contributor
To generate the access token via Postman, I used below parameters:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:<appID>
grant_type:client_credentials
client_secret:<secret>
scope: https://storage.azure.com/.default
Response:
When I ran the below query by including above Bearer token, I got Status 201 Created like below:
PUT https://<storageaccname>.blob.core.windows.net/<container_name>/test.txt
Authorization:Bearer <token>
x-ms-version:2017-11-09
x-ms-blob-type:BlockBlob
Response:
You need to attach the file in Postman before running the query like below:
When I checked the same in Azure Portal, file uploaded to storage account successfully like below:

Get Azure Webjob History - 403 Token invalid

I am trying to retrieve the web job history of an Azure web job via REST using a .NET backend and the OAuth2 credentials flow (as described here
https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-triggered-web-job-history-slot)
How do I need to authenticate correctly?
I retrieve the token as follows:
POST https://login.microsoftonline.com/{MySubscription}/oauth2/v2.0/token
client_id={MyApp}
&grant_type=client_credentials
&scope=https://management.azure.com/.default
&client_secret={myclient_secret}
I get a token back, however I get a 403 error message when I try to retrieve the resource:
GET https://management.azure.com/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}/history?api-version=2021-02-01
Authorization: Bearer {MyToken}
Client '{MyApp}' with object ID '{MyApp}' is not
authorized to perform the action
'Microsoft.Web/sites/slots/triggeredwebjobs/history/read' using the
scope
'/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}'
or the scope is invalid. If access was granted recently, please update
your credentials.
What am I doing wrong?
I already added the API-Permission
The "403 Token invalid" error usually occurs if you missed giving permissions to particular scope (Azure Service Management).
By giving this scope it enables you to access https://management.azure.com
To resolve this error, please follow below steps:
Go to Azure Ad ->your application -> API permissions -> Add permission -> Azure Service Management -> delegated permissions ->User impersonation -> Add
After giving these permissions try to retrieve the resource again, there won't be any error.
Since I didn't find a solution that worked with OAuth2 and the Credentials flow, I got it working with Basic Authentication. The username (userName) and password (userPWD) can be taken from the publishing profile of the respective app service.
GET https://{appservicename}.scm.azurewebsites.net/api/triggeredwebjobs/{jobName}/history
Authorization Basic ....

Authenticate for Azure REST API without login

I have a backend process that doesn't directly interact with the user. I want to access reservations associated with my Azure account but I'm having trouble with the authentication step. I was following the guide here and I managed to get the authentication request to work by calling
https://login.microsoftonline.com/{tenant-ID}/oauth2/token
as a POST with the following x-www-form-urlencoded body:
grant_type=client_credentials&
client_id={client-ID}&
client_secret={client-Secret}&
resource=http://myapp42
However, when I attempt to call:
https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}?api-version=2019-04-01
with the bearer token I received during the authentication step, I get the following error message:
The access token has been obtained for wrong audience or resource 'http://myapp42'. It should exactly match with one of the allowed audiences 'https://management.core.windows.net/', 'https://management.core.windows.net', 'https://management.azure.com/', 'https://management.azure.com'
However, if I modify the resource on the request to be one of these, http://management.core.windows.net/ for instance, the authentication then fails with:
AADSTS500011: The resource principal named https%3A%2F%2Fmanagement.core.windows.net%2F was not found in the tenant named {tenant-ID}. 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 might have sent your authentication request to the wrong tenant.\r\nTrace ID: b54cedea-3804-41cf-bd27-fcf0ed1c4700\r\nCorrelation ID: 2371d375-6c89-4f05-83c9-c4629b3340a8\r\nTimestamp: 2020-02-05 01:59:57Z
How do I authenticate so that I can then get my reservations without having to login?
Update:
The service principal has both the Owner and Contributor roles assigned.
Update 2:
Thanks to #Jim Xu, I was realized that I needed to refrain from url-encoding the URL. That allowed me to get the access token with a value of https://management.azure.com/ for the resource field. However, at this point, when I attempt to call the REST API with the resulting bearer token, I get the following error:
The client '{Object-ID}' with object id '{Object-ID}' does not have authorization to perform action 'Microsoft.Capacity/reservationOrders/reservations/read' over scope '/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}' or the scope is invalid. If access was recently granted, please refresh your credentials
Note: The object ID returned by this error is the one associated with the service principal.
Update 3:
I checked the reservation and it seems that the principal does not have a role in that reservation's access control. However, I also cannot assign the principal a role because it does not show when I search for principals during the role-assigning process.
If you want to call Azure Rest API to get the information of reservation Orders, you need to assign Owner\Contributor for the service principal.(the action needs Microsoft.Capacity/reservationOrders/read permission).
The steps are as below
Get access token
POST : https://login.microsoftonline.com/{tenant-ID}/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&
client_id={client-ID}&
client_secret={client-Secret}&
resource=https://management.azure.com/ or https://management.core.windows.net
Call the api
GET : https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}?api-version=2019-04-01
Authorization: Bearer <token>
For more details, please refer to the issue and the issue
update
If you have assigned role but you still cannot get access token, please try to encode your url.

Power BI always returnig 403 Forbidden

I'm trying do develop an application that makes use of the Power BI API.
The problem is, even though I have a valid authentication token, every API endpoint I tried to access so far returns a 403 (Forbidden) Http status with no content on the response body.
I think the token I'm getting is valid because when I try to use the same token the next day it gives me a "Token expired message".
I'm using a corporative Azure Active Directory account where I'm not an administrator. But I have full access to the Power BI workspaces and Reports on it's web interface.
I'm currently authenticating with Azure AD Oatuh2 v1 but I also tryed v2 with no success (I'm still using v1 because on v2 I'm not sure my scope and resource parameters are right).
Here are the requests I'm sending:
GET
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=<my client id>
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%3A8080/azureLogin/authorize
&response_mode=query
get the authorization code on the redirect at localhost:8080/azureLogin/authorize then
POST https://login.microsoftonline.com/{tenant}/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=<my client id>
&code=<the code I just got>
&redirect_uri=http%3A%2F%2Flocalhost%3A8080/azureLogin/authorize
&client_secret=<my client secret>
As "tenant" I tried both "common" and my organization id.
But when I try to access https://api.powerbi.com/v1.0/myorg/reports with the Authorization: Bearer <token> header. I get a 403 Forbiden response.
On Azure AD I can see my user has given all permissions to this application I registered.
Am I missing something? How can I solve that?
To make the answer visible to others, I'm summarizing the answer shared in comment:
You missed the resource parameter, you are access powerbi, so it should be
resource: https://analysis.windows.net/powerbi/api
The resource is app ID URI of the target web API (secured resource). It may also be an external resource like https://graph.microsoft.com, https://analysis.windows.net/powerbi/api etc. This is required in one of either the authorization or token requests.

Azure Active Directory Getting code 403 with Client Credentials Grant

I have an Azure Function that I have secured using Azure Active Directory (using express settings)
I generated an secret key and was able to get the other bits required (client id, tenant etc).I followed this guide to test the Client Credentials
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-client-creds .
I was able to get an access token but when I try to access the function using the Bearer Token I get error code 403 with 'You do not have permission to view this directory or page.'
How can I fix this? I want to secure my Azure function using a secret key.
Edit ----------
I want to access my Azure function http endpoint.
The requests I have used:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token/
With body:
client_id:{Application Id in Azure AD}
scope:https://{functionname}.azurewebsites.net/.default // This might be the source of the problem
client_secret:{Key Generated}
grant_type:client_credentials
This returns an access token eyJ0eXAiOiJKV1QiLCJhbGciOiJS.....
Then
Get http endpoint of my AzureFunction
https://{functionName}.azurewebsites.net/api/endpoint?Params
The Header contains Authorization Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJS.....

Resources