Azure Apim Bearer token - c#

Hi guys im following the next tutorial from azure:
https://learn.microsoft.com/en-us/rest/api/apimanagement/current-ga/subscription/create-or-update?tabs=HTTP&tryIt=true&source=docs [Azure create or update suscriptions]
I already made it work,but i dont know from where comes from the Bearer token that the example uses
Can anybody explain to me how i can get that bearer token? actually im planning to use this to create api keys from the back end but i dont exactly know from where i can request that bearer token.
I know it says "Azure Active Directory OAuth2 Flow" in the part of security but can anyone explain to me how that works?

you can get the bearer token by following commands in postman:
post https://login.microsoftonline.com/**{tenantid}**/oauth2/token
From your application you can get the tenant id and client id
Azure portal ->Azure active directory ->your app->overview
client secret:
When you send the command you can get the bearer token.
Reference:
Azure REST API: Create Bearer Token - cloudopszone.com

Alternatively, you can generate the Bearer token/access token using cloud shell from the portal by following the below steps
Sign-in to the Azure portal (https://portal.azure.com)
Open cloud shell, select Power Shell
If you have multiple subscription, using set-Azcontext cmdlet set a particular subscription as context to perform operation on that subscription.
Run the cmdlet Get-AzAccessToken this will give you the access token.
Here is the sample output for reference:

Related

Generate Bearer Token using Microsoft Graph

I have Web API built in .net framework 4.6. I secure my API using Azure AD. For the purpose of development, I need to generate token so I can use it for testing and debugging. How can I generate token from Microsoft Graph that I can use to authenticate to my API?
I tried this https://login.microsoftonline.com/{tenantId}/oauth2/token endpoint but the token it generates is not valid. I get 401 using the token from that endpoint.
enter image description here
The error "401 unauthorized" usually occurs when you missed giving resource parameter while generating access token.
If that's the case, you will still get the access token but when you are using the token to authenticate to your API, you will get "Invalid token" error.
To resolve the error, please include below parameters while generating access token:
Make sure to include resource parameter and other required parameters like below:
I tried in my environment, after including the above parameters, I got the access token successfully like below:
If the above solution does not work, try with different grant_type parameter.
For more information, please refer below links:
401 Unauthorized Error–Azure Active Directory (AD) – Microsoft Azure Articles.. (wordpress.com).
Getting Access Token for Microsoft Graph Using OAuth REST API - DZone Security
Azure registered app error: The user or administrator has not consented to use the application with ID - Stack Overflow

MS Graph and Azure Active Directory

Problem: How to authenticate in MS Graph using Azure AAD access token.
Current flow:
My web app has AAD configured with "Log in with AAD"
If I log into AAD my demo app is showing and if I go to https://******.azurewebsites.net/.auth/me
then I get the access_token.
What I tried:
So I tried a couple of things and this was the last, I copied the access_token as code and tried to send it, didn't work.
I'm searching for a solution to silently use the already logged-in user and call MS Graph.
The reason for the error is that you have used the wrong code. Don't try to send the access token as a code, you should request an authorization code in your browser.
https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize?
client_id={client id}
&response_type=code
&redirect_uri={redirect_uri}
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
In addition, redirect_uri is also a required parameter.
For the already logged in user you need follow the below steps for access:
Make sure you have enable the allow access token for the register app as below
Write code to acquire access token for the for the logged in user Reference
Now you can pass this token in other successive call to get the result.

Microsoft Graph API - how to get access token without Authorization Code?

I want my Web API to get an Access Token to then call Microsoft Graph API. I've gone through a few documents and threads but they all talk about a POST method that asks for a Client ID and App Secret created when registering the app on AAD.
I'm following this document here.
My problem is:
What is client_credentials? Where should I get it from? I thought the API is supposed to be working with the secret and the client I'd only.
I appreciate your help.
There's 4 parameters in the HTTP request:
grant_type: in this case, the value is "client_credentials"
client_id: The client id of your app
client_secret: The client secret of your app
resource: The identifier of the API you want a token for, in this case https://graph.microsoft.com
So only client id and secret are needed from your app.
If you use v2 endpoint / MSAL, note there is no resource parameter.
Instead you would use scope=https://graph.microsoft.com/.default.

How to get OAuth2 access token for EWS managed API in service/daemon application

Scenario
I have an Exchange Online environment and service/daemin (no interactive user) application on the Azure VM. Service uses EWS managed API to work with emails in the mailbox of any tenant user. Now EWS client uses Basic authentication that, according to Microsoft, will become unsupported in EWS to access Exchange Online.
Question/Issue
So, I need to find a way to get valid access token for service/daemon application to use with EWS managed API.
My findings
The following article shows an example of using OAuth 2.0 with EWS managed API. This example works, but it uses interactive method of getting consent (sign-in form appears allowing user authenticate themselves and grant requested permission to application) that is not suitable for service/daemon app scenario, because there is no interactive user.
For service/daemon application I need to use client credential authentication flow.
Registered application
Using admin account on https://aad.portal.azure.com portal I registered application with Azure Active Directory. Added client secret for registered application.
Aforementioned article uses https://outlook.office.com/EWS.AccessAsUser.All as a scope. But I did not find permission with such a URL on the portal. I found only the following permissions under Office 365 Exchange Online > Application permissions > Mail:
https://outlook.office365.com/Mail.Read Allows the app to read mail in all mailboxes without a signed-in user
https://outlook.office365.com/Mail.ReadWrite Allows the app to create, read, update, and delete mail in all mailboxes without a signed-in user.
I added both of them and granted admin consent for all users.
Getting access token
For testing purposes and simplicity I did not use any auth libraries (ADAL, MSAL etc.). I used Postman to get access token, then set token variable in debug (see code snippet later in the post).
I tried different endpoints to get acess token.
OAuth 2.0 token endpoint (v2)
POST: https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token
grant_type=client_credentials
client_id=***
client_secret=***
scope=https://outlook.office.com/EWS.AccessAsUser.All
Sending this request produces the following error response:
AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://outlook.office.com/EWS.AccessAsUser.All is not valid.
I tried changing scope to https://outlook.office.com/.default. Access token was returned, but it appeared to be invalid for EWS. EWS client throws 401 error with the following value of x-ms-diagnostics response header:
2000008;reason="The token contains no permissions, or permissions can not be understood.";error_category="invalid_grant"
OAuth 2.0 token endpoint (v1)
POST: https://login.microsoftonline.com/<TENANT_ID>/oauth2/token
grant_type=client_credentials
client_id=***
client_secret=***
resource=https://outlook.office.com
Access token was returned, but also appeared to be invalid for EWS. EWS client throws 401 error with the same value of x-ms-diagnostics response header as described ealier in #1.
Use aquired access token with EWS managed API
Here is code sample that I used to test EWS client with access token acquired in Postman:
var token = "...";
var client = new ExchangeService
{
Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
Credentials = new OAuthCredentials(token),
ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress,
"user#domain.onmicrosoft.com"),
};
var folder = Folder.Bind(client, WellKnownFolderName.SentItems);
We had a similar problem: We wanted to use a Service Account to connect to a single mailbox and just doing some stuff with the EWS API (e.g. searching in the GAL) and the full_access_as_app seems like an overkill.
Fortunately it is possible:
Follow the normal "delegate" steps
And use this to get a token via username/password:
...
var cred = new NetworkCredential("UserName", "Password");
var authResult = await pca.AcquireTokenByUsernamePassword(new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" }, cred.UserName, cred.SecurePassword).ExecuteAsync();
...
To make this work you need to enable the "Treat application as public client" under "Authentication" > "Advanced settings" because this uses the "Resource owner password credential flow". (This SO answer helped me alot!)
With that setup we could use a "tradional" username/password way, but using OAuth and the EWS API.
You can protect your client application with either a certificate or a secret. The two permissions that I needed to get this to work were Calendars.ReadWrite.All and full_access_as_app. I never tried acquiring my token via PostMan, but use AcquireTokenAsync in Microsoft.IdentityModel.Clients.ActiveDirectory. In that call, the resource parameter I use is https://outlook.office365.com/. It's pretty simple once you know all the little twists and turns. And full disclosure: I was one lost puppy until MSFT support helped me through this. The doc on the web is often outdated, conflicting, or at best, confusing.
You need to register your app in Azure and use certificate based authentication. https://blogs.msdn.microsoft.com/emeamsgdev/2018/09/11/authenticating-against-exchange-web-services-using-certificate-based-oauth2-tokens/
I run into the same issue while following Microsoft official docs for OAuth 2.0 client credentials flow
According to the Microsoft identity platform and the OAuth 2.0 client credentials flow, the scope "should be the resource identifier (application ID URI) of the resource you want, affixed with the .default suffix" (see default scope doc).
So the question is how to convert https://outlook.office.com/EWS.AccessAsUser.All into the resource identifier.
Experimentally I manage to make it working using scope=https://outlook.office365.com/.default. I granted full_access_as_app (Office 365 Exchange Online / Application permissions) and got administrator consent for it.
I did face this issue while implementing OAuth for EWS. My application is not using EWS Managed API. Here is what all I did to make it working.
Added permission Office 365 Exchange Online > full_access_as_app to application.
Acquired access token for scope https://outlook.office365.com/.default.
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
form-data = {
client_id,
client_secret,
grant_type: 'client_credentials',
scope: 'https://outlook.office365.com/.default',
};
Added access token as Authorization header and ExchangeImpersonation SOAP header to the request.
<SOAP-ENV:Header>
<t:ExchangeImpersonation>
<t:ConnectingSID>
<t:PrimarySmtpAddress>user#domain.com</t:PrimarySmtpAddress>
</t:ConnectingSID>
</t:ExchangeImpersonation>
</SOAP-ENV:Header>
Late answer, but since this seems to come up, and I was just working with this... why not.
If you use Microsoft's v2.0 URLs for OAUTH2 (https://login.microsoftonline.com/common/oauth2/v2.0/authorize and .../common/oauth2/v2.0/token) then the scope for Office 365 EWS is:
https://outlook.office365.com/EWS.AccessAsUser.All
You'll probably want to combine this scope with "openid" (to get the signed in user's identity) and "offline_access" (to get a refresh token). But then offline_access may not be necessary when using client credentials (because you don't have to prompt a human user for them every time you need an access token).
In other words:
params.add("client_id", "...")
...
params.add("scope", "openid offline_access https://outlook.office365.com/EWS.AccessAsUser.All")
If using v1 OAUTH2 URLs (https://login.microsoftonline.com/common/oauth2/authorize and .../common/oauth2/token) then you can use a "resource" instead of a "scope". The resource for Office 365 is https://outlook.office365.com/.
Or in other words:
params.add("resource", "https://outlook.office365.com/")
Note that in the latter case, you're not asking for any scopes (it's not possible to combine "resource" with scopes). But the token will automatically cover offline_access and openid scopes.
I used this method successfully:
Install Microsoft Authentication Library module ( MSAL.PS)
https://www.powershellgallery.com/packages/MSAL.PS/4.2.1.3
Configure Delegate Access as per MSFT instructions: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
Configure ApplicationImpersonation for a service account as normal
Grab your token
$cred = Get-Credential
$clientid = ""
$tenantid = ""
$tok = Get-MsalToken -ClientId $clientid -TenantId $tenantid -UserCredential $cred -Scopes "https://outlook.office.com/EWS.AccessAsUser.All"

Azure AD Graph API Bearer Token with ADAL JS

As Learning application , i am using AngularJS,ADAL js and WebAPI as Mentioned in this post.
Angularjs-authentication-using-azure-active-directory-authentication-library-adal
Tutorial is very neat and clean for the implementation. After the authentication i am trying to add a User in the Azure AD[The same AD i validated my credentials against].
To work with Azure AD there is Azure AD Graph API.which requires a Bearer Token.
To get The Bearer token AuthorizationContext will be used.
var authcontext = new AuthenticationContext(GraphRequest.authority);
AuthenticationResult authResult = authcontext.AcquireToken(GraphRequest.apiResourceId,
GraphRequest.clientId, GraphRequest.redirectUri);
As Authentication context is in control , so it is asking again credentials with popup. but i already have a claimPrincipal.
Is there any way i can use ClaimPrincipal to get the bearerToken ?
Have you had a chance to take a look at our public samples on GitHub?
Something like this might be useful for you to look at:
https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi
Otherwise, in general, you cannot take an ID Token and then use it to upgrade to an access token. What you can do instead is skip that login prompt, and just do the code you pasted above which obtains an access token, which can be turned into an ID token.
I hope this makes sense, please feel free to reach out with any further questions.
Shawn Tabrizi

Categories

Resources