How to generate oauth token for webapi without using client id and client secret - azure

I have deployed one webapi into azure. After that I have register my API into Azure AD.
I got my API client-id and client-secret, now i just want to test my API not like
3rd application will access it so what will be recourse id in this case.
I have used oauth for authentication into that webapi.
I want to test that webapi so into POSTMAN i used this url to generate oauth token
which i will pass as header Authentication bearer token.
step 1 -
https://login.microsoftonline.com/{{OAuth_Tenant}}/oauth2/token
in header -
grant_type:client_credentials
client_id:{{client_id}} // i have my API client-id
client_secret:{{client_secret}} // i have my API client-secret
resource:{{resource}} // i have my API client-id
when i generate token using above values and send that bearer token it fail error unauthorized.

You need to register an app in Azure Active Directory to acquire access tokens.
Register an app there, and you can find the client id/application id there.
Then you can create a key for the app, that's your client secret.
Finally the resource should be the client id or app id URI for your API's app registration in Azure AD.
To implement this according to best practices, you'll also want to look into defining app permissions for your API, so you can then assign privileges to apps to call your API.

Related

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.

Azure AD OAuth Client Credentials Grant flow

Trying to set up Azure AD OAuth client credentials grant flow for my web api. I'm following the document in https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow. I have to expose my API to a 3rd party. I've created the APP in Azure AD (this is for the client that is requesting my API), generated the secrets and was able to get a response from oauth2/token endpoint. My questions are below:
What is the best way to validate the token? Is it by passing the JWT
(bearer token) as a HTTP header to my API, and then using the SDK to
validate the token
(System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler)? I'm using
C#.
What is the significance of Azure AD -> App Registrations -> "My
API App" -> under Manage, Expose an API? It has an option to
"Authorize client applications". How could I use this feature to
conditionally block and approve the client applications?
I will have to share the secret, client id and the App Id Uri with the 3rd party for them to generate the token and I will validate the token when I receive it.
You're on the right track.
This answer, Azure AD OAuth client credentials grant flow with Web API AuthorizeAttribute Roles, will walk you through one way to do this, using the roles claim in the token to authorize the call.
You will need to:
define roles
create an App registration for each 3rd party
assign their application to your desired roles
You can then use the AuthorizeAttribute to map which roles can execute which controllers/actions, like so:
[Authorize(Roles = "Reader,Requester,Editor,Approver,Administrator")]
Token validation
Once you complete token obtaining flow, you receive a JWT bearer access token. From token consuming end (your service), you need to perform a JWT validation. This is done by validating JWT signature and Claims. One of the most important claim you validate is the audience (aud) claim which must be the identifier (ex:- your service's URL, an ID) unique to token receiving service. Where you register this ? That's your second question.
Please read through MS's guide on token validation which explains key points - Microsoft identity platform access tokens
Service registration
This is where you register valid token receivable endpoints (ex:- your api app). If you check your token request, you provide resource parameter which must match to registered identifier. This allows Azure to validate the token request and issue an access token the mentioned resource. You find this as aud claim in the token. Hope you got the connection now.
App secret
No, only the token obtaining party require the client credentials. Your API or any token consuming party does not need the secret. They only require a valid access token and token signing certificate details. certificate details are exposed at jwks_uri in openid-configuration endpoint.

Azure AD: id_token as bearer token

I have an application registered in Azure AD.
If I am using the same Application ID at the level of Web API and at the level of client (SPA application), why do both Azure AD auth libraries
(ADAL JS for Azure AD v1 and MSAL.js for Azure AD v2)
use ID token as bearer token when calling Web API, instead of requesting and using an access token? Doesn't this go against the spec?
According to official documentation and this might be your case.
"The OAuth 2.0 implicit flow in Azure AD is designed to return an ID token when the resource for which the token is being requested is the same as the client application. In other words, when the JS client uses ADAL JS to request a token for its own backend web API registered with same App ID as the client, an ID token is returned and cached by the library. Note that in this case the resource should be set to the App ID of the client (App ID URI will not work). This ID token can then be used as a bearer token in the calls to your application's backend API."
You can find more about this here!
https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/Acquire-tokens

Authenticate Azure app service with AAD custom login in mobile app

I have created app service for mobile app. Then i have added Authentication to the app service. Then Selected Authentication type as "Log on with Azure AD". It is working fine.
Is it possible to have custom login page instead of browser based login screen?
I was able to get the token by using https://login.microsoftonline.com//oauth2/token. But not able to authorize the app service with this bearer token.
Is it possible to have custom login page instead of browser based
login screen?
This page is the authentication endpoint of AzureAD. Though it can be configured by Company branding, I think it cannot be customlized by yourself for Moblie APP.
I was able to get the token by using
https://login.microsoftonline.com//oauth2/token. But not able to
authorize the app service with this bearer token.
Authencation/Authorization for Web App is a feature that securing Web App behind those IDPs, NOT just like other azure resources you can use REST API to access it. I understand what you want to do . But this action is not recommended or supported.
I was able to get the token by using https://login.microsoftonline.com//oauth2/token. But not able to authorize the app service with this bearer token.
As juunas answered, your token may does not match the AAD provider you configured on Azure Portal. Details you could follow here to check your configuration. Moreover, you could use https://jwt.io/ to decode your access_token and validate the related properties (e.g. the aud should be the clientId you configured on Azure Portal,etc.).
As App Service Authentication / Authorization (EasyAuth) states as follows:
Users who interact with your application through a web browser will have a cookie set so that they can remain authenticated as they browse your application. For other client types, such as mobile, a JSON web token (JWT), which should be presented in the X-ZUMO-AUTH header, will be issued to the client. The Mobile Apps client SDKs will handle this for you. Alternatively, an Azure Active Directory identity token or access token may be directly included in the Authorization header as a bearer token.
For Azure Web App or Azure Mobile App, you could just access your endpoint as follows:
https://{your-app-name}.azurewebsites.net/api/values
Header: Authorization:Bearer {the id_token or access_token of AAD}
Or
https://{your-app-name}.azurewebsites.net/api/values
Header: x-zumo-auth:{authenticationToken}
Moreover, if you retrieve the access_token in your mobile app, you could also use it to retrieve the authenticationToken and use the authenticationToken for communicating with the backend endpoint.
POST https://{your-app-name}.azurewebsites.net/.auth/login/{provider-name,for your scenario, it would be AAD}
Body: {"access_token":"<your-access-token>"}
For your mobile client, you could use the client for Azure Mobile Apps, details you could follow here. Also, you could follow Authenticate users to understand the client-flow and server-flow authentication for App Service Authentication.
As Wayne Yang said, customization of the login page is limited to logos and some text.
I'm not sure if you can use the "Easy Auth" for APIs.
You might need to actually implement the authentication in your app.
In that case your API would validate the incoming JSON Web Token so that its signature is valid and that the audience and issuer are what is expected.
Most frameworks have JWT authentication available, so it mostly comes down to configuring that properly.

MobileServiceClient InvokeApiAsync gets 401 while try to access asp.net core web api

I have a Xamarin Forms app that intereacts with a Asp.net Core Web api hosted on Azure App Service with client authentication flow with Azure B2C authentication.
The app can login succesfully to the Azure with the LoginAsyc (I get the idtoken) but when I try to invoke a service that requires authorization using the MobileServiceClient I get a 401. The api is called using the InvokeApiAsync.
If I invoke a an api method that does not require authorization it works fine.
I opened the Azure logs, and only see 401 error.
Any idea how to call this secure action method from Xamarin using the MobileServiceClient.
Please help
David
The app can login succesfully to the Azure with the LoginAsyc (I get the idtoken) but when I try to invoke a service that requires authorization using the MobileServiceClient I get a 401. The api is called using the InvokeApiAsync.
According to your description, I assumed that you are using App Service Authentication / Authorization. For Client-managed authentication, you directly contact the AAD identity provider and retrieve the id_token or access_token. At this time, you could just access the authorized endpoint as follows:
https://{your-app-name}.azurewebsites.net/api/values
Authorization: Bearer {aad id_token or access_token}
Note: When constructing the MobileServiceClient, you could pass your custom DelegatingHandler to append the bearer token before sending request(s) to your Azure backend.
I just created a single Native app in my B2C tenant and use MSAL to retrieve the id_token or access_token as follows:
var authority = "https://login.microsoftonline.com/tfp/{Tenant}/{Policy}";
PublicClientApplication IdentityClientApp = new PublicClientApplication("{native-app-id}", authority);
IdentityClientApp.RedirectUri = $"msal{native-app-id}://auth";
var scopes = new string[] {
//"https://bruceb2c.onmicrosoft.com/EasyAuthB2CApp/user.read"
""
};
var result=await IdentityClientApp.AcquireTokenAsync(scopes);
Note: I just created a single native app, the parameter scopes in AcquireTokenAsync method does not support the clientId, so I just pass the empty scopes, at this point, you would not receive the access_token, you just need to use the id_token as the bearer token to access your Web API. For the Web API web app, I used the native app to configure my AD authentication on Azure Portal.
Moreover, you could create a native aad app for your mobile client and a WebAPI aad app for your azure web app. At this time, you could specify the valid scopes for your native aad app to access the WebAPI app. Then, you would retrieve the access_token, at this time you need to set the WebAPI app id as the Client ID or add it to the ALLOWED TOKEN AUDIENCES list on Azure Portal.
In summary, you need to make sure the aud property in the id_token or access_token matches your Azure Active Directory Authentication Settings on Azure Portal. Note: You could use https://jwt.io/ to decode the token and check the related properties.
Moreover, for client flow authentication using LoginAsync, you need to pass the access_token to log in with your web app, then you would retrieve the authenticationToken. And the mobile client library would add the authenticationToken as the x-zumo-auth header to the subsequent requests (e.g. using MobileServiceClient.InvokeApiAsync).
Additionally, here are some tutorials, you could refer to them:
App Service Auth and Azure AD B2C
Integrate Azure AD B2C into a Xamarin forms app using MSAL
Azure AD B2C: Requesting access tokens
ASP.NET Core 2.0 web API with Azure AD B2C using JWT Bearer middleware

Resources