List Queues/Topics of Azure Service Bus using Rest API with SharedAccessKey - azure

I am trying to list the Queues/Topics in an Azure Service Bus using the REST API.
When I try to connect I just get back a blank feed saying "This is the list of publicly-listed services currently available".
I am using the RootManageSharedAccessKey in the portal (for dev only, I can create a more restricted key later) so it should have all the access rights that I need, I just can't seem to get it to return anything. This documentation seems to suggest that this will work, but there's no actual working examples, just theoretical responses.
I have tried doing a GET request with the signature in the URL like this:
https://myservicebusnamespace.servicebus.windows.net/$Resources/Queues;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=MYSHAREDACCESSKEY
I have also tried doing it like this:
https://myservicebusnamespace.servicebus.windows.net/$Resources
and then setting the Authorization header to
WRAP access_token="MYSHAREDACCESSKEY="
Both times I just get this back
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">Publicly Listed Services</title>
<subtitle type="text">This is the list of publicly-listed services currently available.</subtitle>
<id>uuid:6a5d438d-1793-451b-be41-XXXXXXXXXXXX;id=XXXXXX</id>
<updated>2020-06-28T13:03:04Z</updated>
<generator>Service Bus 1.1</generator>
</feed>
If I change the url slightly to be:
https://myservicebusnamespace.servicebus.windows.net/$Resources/Queues/
I get a slightly different response back of:
<Error>
<Code>401</Code>
<Detail>claim is empty. TrackingId:c40a2bd2-490d-4b5b-adde-33bc89aa84ff_G36, SystemTracker:myservicebusnamespace.servicebus.windows.net:$Resources/Queues, Timestamp:2020-06-28T13:27:40</Detail>
</Error>
Which seems to suggest that I am not authorised, or I am missing something. If I add an acutual queue name to the end of that url, it goes back to the original response.
I believe there is another way to get this information by using subscription ids and pem keys... using the management urls (https://management.core.windows.net/{subscription ID}/services/ServiceBus/Namespaces/{Namespace}/Topics/)
but this should all be possible using the format above, I just can't figure out the exact format required.
EDIT/UPDATE: If I don't include my auth claim, the result is exactly the same, suggesting that it's not seeing my auth claim or it's invalid. However if I include it, and just make it the token, without the WRAP bit at the start, I get an exception saying
<Error>
<Code>401</Code>
<Detail>MalformedToken: Invalid authorization header: The request is missing WRAP authorization credentials. TrackingId:7be2d7f0-c165-4658-8bf1-ea104c43defc_G28, SystemTracker:NoSystemTracker, Timestamp:2020-06-28T13:33:09</Detail>
</Error>
So it's like it's reading it then ignoring it?

If you want to list queues or topics we can use Azure service bus service rest api or Azure Resource Manager Rest API. For more details, please refer to the following steps
Azure service bus service rest api
Generate SAS token. For more details, please refer to the document
For example, I use python to create sas token
import hmac
import time
import hashlib
import base64
import urllib
sb_name='bowmantest'
// your entity path such as $Resources/topics (list topics) $Resources/queues(list queues)
topic='$Resources/topics'
url=urllib.parse.quote_plus("https://{}.servicebus.windows.net/{}".format(sb_name,topic))
sas_value='' // your share access key
sas_name='RootManageSharedAccessKey' // your share access rule name
expiry = str(int(time.time() + 10000))
to_sign =(url + '\n' + expiry).encode('utf-8')
sas = sas_value.encode('utf-8')
signed_hmac_sha256 = hmac.HMAC(sas, to_sign, hashlib.sha256)
signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest()))
auth_format = 'SharedAccessSignature sig={0}&se={1}&skn={2}&sr={3}'
auth=auth_format.format(signature,expiry,sas_name,url)
print(auth)
Call the rest API
1). list Queues
GET https://<namespace name>.servicebus.windows.net/$Resources/queues
Authorization <sas token>
2). List topics
GET https://<namespace name>.servicebus.windows.net/$Resources/topics
Authorization <sas token>
Azure Resource Manager Rest API
create a service principal and assign Azure RABC role to the sp(I use Azure CLI)
az login
#it will create a service principal and assign contributor role to the sp
az ad sp create-for-rbac -n "jonsp2"
Get Azure AD token
POST /{tenant}/oauth2/v2.0/token HTTP/1.1 //Line breaks for clarity
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=<app id>
&scope=https://management.azure.com/.default
&client_secret=<app password>
&grant_type=client_credentials
call the rest API
List Queues
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues?api-version=2017-04-01
Authorization Bearer <AD token>

Related

MS Subcriptions REST API returns empty value

I register a new app to my Azure tenant and then use the Subscription REST API below to get my subscription id. But, it returns an empty value.
Is this a bug of the REST API, or the app is missing some required configurations?
https://learn.microsoft.com/en-us/rest/api/resources/subscriptions/list?tabs=HTTP
I tried to reproduce the same in my environment and got below results:
I registered one Azure AD application and granted API permission like below:
I generated the access token via Postman using below parameters:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
grant_type:client_credentials
client_id:<appID>
client_secret:<secret>
scope: https://management.azure.com/.default
Response:
When I used the above token to get subscriptions, I got same response as you like below:
GET https://management.azure.com/subscriptions?api-version=2020-01-01
Authorization: Bearer <token>
Response:
To get the desired results, make sure to assign required role like Reader to the service principal under your subscription like below:
Go to Azure Portal -> Subscriptions -> Your Subscription -> Access control (IAM) -> Add role assignment
Now I generated token again and got the subscription details like ID successfully with below API call:
GET https://management.azure.com/subscriptions?api-version=2020-01-01
Authorization: Bearer <token>
Response:
If you want to list all subscriptions, then assign Reader role to your service principal under management group level instead of specific subscription.

Azure AD is not returning token : Unknown Host Error

I am trying to grant access to IoT Hub based on Azure AD. But when I try to get token, it is throwing this error in Postman
####### Update ######
I have already created the Application in Azure AD
The resource field should be the static ID of all IoT Hub service principals. Try this instead of the hostname:
89d10474-74af-4874-99a7-c23c2f643083
Here is another approach:
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Azure AD application like below:
To generate token via Postman, I used the below parameters:
POST https://login.microsoftonline.com/TenantID/oauth2/token
client_id:14ad98e6-8b3d-4774-a2ad-XXXXX
client_secret:XXXXXX
resource:https://iothubs.azure.net
grant_type:client_credentials
Response:
When I decoded the above token, I can see the aud as https://iothubs.azure.net like below:
The 400 Bad request error usually occurs if you have passed any invalid URL while generating the token. Make sure to pass the valid parameters.
Try sending the request again in Postman and check if the access token is generated or not.
Alternatively, you can also replace the resource by 89d10474-74af-4874-99a7-c23c2f643083 as suggested by Matthijs van der Veer like below:
Decoded token Response:

How to Fetch Token to access APIM from Function App with Managed identity

I am trying to access APIM from Azure Function and want APIM to authenticate through Managed Identity Token. I have assigned system assigned identity to the function app.I am following this (sample)[https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#asal] to generate token. In the below line if I give "https://vault.azure.net" to GetAccessTokenAsync method I am getting the token. but I want the audience to be APIM so I provided https://azure-api.net like mentioned in the last line. but I am getting exception. how can I provide the APIM Url to fetch the access token?
using Microsoft.Azure.Services.AppAuthentication;
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://azure-api.net");
An Update. I think something wrong with listing the resources. because when I give the proper resource name it says resource doesnt exist in the tenant though I can see the subscription is under the same tenant when I run through az cli.
As I mentioned in the comment, you need to Register an application in Azure AD to represent the API, then you can get the token for it(i.e. with the Application ID URI in the previous link).
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("<Application ID URI>");
Something you need to know:
You can use azureServiceTokenProvider to get the token for https://vault.azure.net, https://managment.azure.com, because they are all the APIs exposed by Microsoft, i.e. azure keyvault rest api and azure management rest api, essentially they are all AD App registered by Microsoft, so if you want to get the token for your own API, you need to register the AD App first to represent the API first.
Also, when you use managed identity to get the token, essentially it uses the client credential flow to get the token, actually the managed identity is a service principal(i.e. enterprise application) managed by azure. Remember to leverage the app role if you need to validate the roles claim when you get the access token.

Authenticated REST API call to Azure Service Bus using Managed Identity

Azure Service Bus supports managed identity access, however the only method I've found to for example send a message to a queue is using this approach that requires code and the Service Bus SDK:
var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
QueueClient sendClient = new QueueClient($"sb://{Config.Namespace}.servicebus.windows.net/", Config.Queue, tokenProvider);
await sendClient.SendAsync(new Message(Encoding.UTF8.GetBytes(messageInfo.MessageToSend)));
await sendClient.CloseAsync();
Sources:
https://github.com/Azure-Samples/app-service-msi-servicebus-dotnet
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-managed-service-identity
I'm looking for a way to do the same thing with a REST API call from within an Azure API Management policy. I've granted APIM, role based access to Service Bus and I'm able to get a token back, but I get this error back from Service Bus when attempting the REST API call with the managed identity token passed in the Authorization header:
MalformedToken: The credentials contained in the WRAP header are not well-formed.
It looks like Service Bus might only support WRAP or SAS tokens at this point with their REST API: https://learn.microsoft.com/en-us/rest/api/servicebus/send-message-batch
But then again how is this working behind the scenes?
TokenProvider.CreateManagedServiceIdentityTokenProvider()
Seems like it should be possible with the REST API.
It seems in the SDK they don't specify it as Authorization: Bearer tokenabcdef..... but as Authorization: tokenabcdef. Which is a bit unusual.

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.

Resources