IoT Central - How to Generate API token programatically - azure-iot-central

I wanted to use IoT Central REST API call.
But for using any REST API calls, we need an Authorization token.
So I want a way how we can create a new API Token in IoT Central programmatically.
From the below tutorial, found two ways :
https://learn.microsoft.com/en-us/learn/modules/manage-iot-central-apps-with-rest-api/2-authorize-api
In the Administration section in your application's web UI on the IoT Central portal.
Using the IoT Central REST API.
To generate an API token using the REST API, you must already have an Application administrator API token or a bearer token to authorize the call.
Now for getting bearer token, we have to use az cli which is not a feasible option for our approach. So instead of manually creating API token, we want a way to generate it programatically
Could you please give me some references on how to achieve this

A bearer token is associated with an Azure Active Directory user account, therefore you need to be authenticated to retrieve it.
With the bearer token you can generate an IoT Central Api Token programatically. The REST GET call is described here: https://learn.microsoft.com/en-us/rest/api/iotcentral/apitokens/get
See also: Authentication vs authorization doc

Related

Azure easy auth get user role based on AD user Id ASP.net core app WebAPI

I'm following link to make authentication and authorization.
I able to create successfully token based on https://login.microsoftonline.com/{tenantID}/oauth2/token
After that I calling GET API using sayhello. It's everything fine, but I want based on token and UserId/Password of AD user get user role.
I search a lot but not getting any concrete solution.
To decode the Azure Active Directory JWT token using the tool, you can use this online decode tool JSON Web Tokens - jwt.io.
Here is an example covered of how to verify and decode Azure Active Directory Token, refer this article.
If you want to manually decode a bearer token using azure active directory, you can use JwtBearer or AddAzureADBearer middleware to validate the access token.
Please refer this thread which contains code to decode a bearer token.

Incomplete bearer token when using authentication-managed-identity tag in azure api management

I've been trying to expose an API through azure API Management and I can't figure out what I'm doing wrong. Here's the situation:
My API is going to be called from an external application
They don't have an Azure Account in the same tenant
I want to enable external calls for my API by just using a subscription key (hence, why I'm using API Management), but also want to keep my actual API secured with Azure AD.
I have an API which is secured with Azure AD using OAuth2 and published into a Windows AppService
I have an App registration for that API, which i use to authenticate (it works from postman, for example)
app registration
I have Managed Identities turned on and permissions set.
I have added the API in API management
I added the authentication-managed-identity inbound rule, used the API Id Uri of the app registration as the resource value for it.
Api Management Config
When testing an endpoint from the APIM interface, I can successfully get a bearer token, but I get a 500 exception from the API which says: Neither scope or roles claim was found in the bearer token
bearer response
Here is the decoded bearer token, it doesn't have a scp attribute
bearer decoded
I'm not sure where I can specify a scope. If I use the full scope uri (api://guid/access.api.management) it will fail when trying to get a bearer token (The resource principal named api://guid/access.api.management was not found in the tenant).
I've even tried adding the Owner role to the APIM Identity for the AppService.
Maybe I'm not using this correctly, I'm pretty new at using Azure cloud and API Management so any suggestions are welcome.
Thanks.
You have expose an api protected by Azure, and currently you have an api application. Next, you need to create another application that represents the client, and then add the client application to the api application.
Next, go to the client application.
Under 'API permissions' click on 'Add permission', then click on the 'My APIs' tab.
Find your api application and select the appropriate scope.
Click 'Add permissions'.
Grant admin consent for your APIs.
Next, you need to use the auth code flow to obtain an access token,which requires you to log in to the user and obtain the authorization code, and then use the authorization code to redeem the access token.
1.Request an authorization code in the browser.
https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize?
client_id={client app client id}
&response_type=code
&redirect_uri={redirect_uri}
&response_mode=query
&scope=api://{api app client id}/{scope name}
&state=12345
2.Redeem token.
Parse the token:
I managed to get it working using the client credentials flow and storing the client secret in key vault.

How to generate bearer token to activate PIM in azure

I am using the below REST API to enable azure PIM at the moment.
API endpoint : https://api.azrbac.mspim.azure.com/api/v2/privilegedAccess/azureResources/roleAssignmentRequests
Body:
{
"roleDefinitionId":"sdfsa4324-7b46-sdfa234-8db9-c32423354",
"resourceId":"243-4a58-4sdf1e-a0f4-234234dfds",
"subjectId":"sdfasd-9af3-42f5-9699-dfasd243",
"assignmentState":"Active",
"type":"UserAdd",
"reason":"Evaluate Only",
"ticketNumber":"Evaluate Only",
"ticketSystem":"Evaluate Only",
"schedule":{"type":"Once","startDateTime":null,
"endDateTime":null,"duration":"PT0M"},
"linkedEligibleRoleAssignmentId":"2423asdf-c271-4342342-8859-11243dfsaf",
"scopedResourceId":null
}
The problem I am facing at the moment is I am not sure how to generate the bearer token automatically to pass as an authorization header. Currently, I am just fetching the token from the Chrome developer console. Can anyone help me to point an API in which I can use my creds and generate a bearer token which I can use for PIM?
Thanks,
Tintu
According to your description, I assume that you'd like to call an API to enable PIM, so you need an access token, here an official doc recommend you to use MSAL to obtain the token you need.
we recommend you use the supported Microsoft Authentication Libraries
(MSAL) instead to acquire tokens and call secured web APIs. Also take
a look at the sample apps that use MSAL.
I have another answer which used msal.js to generate access token for calling graph api for azure key vault, the difference is the scopes, and according to this document, it says the api soope is :
Directory.AccessAsUser.All Directory.Read.All Directory.ReadWrite.All PrivilegedAccess.ReadWrite.AzureAD
So you need to create an azure ad application and add above api permissions and change the 'scope' in the code. And if you need a sample in other program language, you can refer to this doc to choose another sample.
Before you compose the code, I think you can generate a test token to test if this token could help you to call the api, using tools like postman.

Problem generating valid oauth2 token to access PowerBI APIs

The Setup :
Am trying to access Azure PowerBI based APIs using console application since my company wants to Suspend/Resume PBI capacity to optimize costing.
Have been successful in accessing those apis as per official documentation API Emulator Window, it works by perfect as it just asks with a authentication window for username and password of my outlook account and it generates authentication token implicitly successful.
When i tried to implement calling api from my console application which will be triggered automatically scheduled, there are ways to generate authentication token programmatically. Following are the methods i used to generate the same before accessing the PBI APIs.
Approach #1 : Generating token by using Azure Active Directory Authentication Libraries..
This approach asks to add AAD authentication libraries via Nuget, upon adding the same and it goes unsuccessful as the method AcquireTokenAsync takes no parameters but tutorial specified 4 parameters to be feed into this method (function overloading missing?). So i couldnt generate token using this approach. Surely a library version problem but the official MS documentation didnt explain anything above versions available over same.
Approach #2: Authorize Active Directory without dialog box StackOverflow Question with marked as answer
This approach upon calling HTTPResponseMessage, it gets hung up without going next line or catch statement.
Approach #3: Trying to emulate token generation using POSTMAN and using the generated token on my console app to check accessibility.
This approach gives a successful token generation but when using the generated token in the console app, it says unauthorised token.
Doubt Part:
Have generated ClientID, ClientSecretID and TenantID in Azure using AppRegisteration but dont know how this gets associated with PowerBI Service in azure. Do Azure Active Directory comes in place betweeen PBIService and AppRegisteration? Based on generated AppRegisteration details have tried to access this authentication api (https://login.microsoftonline.com/tenantId/oauth2/token) to generate token. This is successfully generates a token but miserably getting failed with unauthorised access on PBI api.
Am i badly missing something? will be helpful on what wrong about this concept of accessing PBI based API getting authenticated via console app. Asusual PBI community sites didnt help much.
1. How to manage Azure Power BI Embedded capacity
If you want to manage Azure Power BI Embedded capacity with rest API, please refer to the following steps.
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 Token
Post https://login.microsoftonline.com/tenantId/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type =client_credentials
&client_id=<sp app id>
&client_secret=<sp app password>
&scope=https://management.azure.com/
Call Rest API
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/suspend?api-version=2017-10-01
Authorization: Bearer <token>
2. How to call Power BI rest api
If you want to call Power BI rest api, please refer to the document and the document.
The detailed steps are as below
Register Azure AD application in Azure portal
Configure API permissions
Test (I test in postman)
a. get access token
b. call API
Suspend/Resume PowerBI API is described over here:
https://learn.microsoft.com/en-us/rest/api/power-bi-embedded/capacities/suspend
https://learn.microsoft.com/en-us/rest/api/power-bi-embedded/capacities/resume
Did you read the whole Azure REST API Reference?
All steps needed to send an HTTP request are documented over here:
https://learn.microsoft.com/en-us/rest/api/azure/

IDX10503: Signature validation failed with Microsoft Graph and Azure AD

I have an ASP.NET Core WebApi which uses Azure AD Bearer Tokens (passed by the Frontend, acquired using adal.js).
Currently, we are using the Azure AD Graph API and everything works fine.
As recommended by Microsoft, we would like to migrate from Azure AD Graph API to Microsoft Graph.
I changed the audience from https://graph.windows.net to https://graph.microsoft.com both in the API and Frontend. I can successfully acquire a token, which looks almost the same as the old one when decrypted in jwt.io, but when I pass it to the API I get:
Bearer was not authenticated. Failure message: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey
Did I miss something? As far as I know, it should be possible to sign in using the Microsoft Graph, right?
If I understood correctly, you have configured your API audience as the MS Graph API audience.
You should not do this.
Firstly MS Graph API access tokens are bit special and you should not try to validate them,
secondly because your API is not MS Graph API.
Your front-end should acquire an access token for your API.
This requires you to configure your API audience as either its client id or Application ID URI (or both).
Azure AD allows the front-end to acquire the token using either of those.
The API can then exchange that for an MS Graph API token using the On-Behalf-Of flow.

Resources