How to implement authentication and authorization using MSAL.net - azure

Please help me.
To login into Azure active directory how to use MSAL.Net library in my login page of my website.I am seeing very big samples online but I didnt find small peace of code which makes me to understand MSAL.

MSAL Library is just an implementation for enabling developers to acquire tokens from the Microsoft identity platform endpoint.
If you want to use MSAL to acquire a token, you need to:
Register an application in Azure AD.
Add target API, and grant consent to select permissions.
Generate a secret key.
Then you can get a token as Acquire a token and call Microsoft Graph API.
However, I think what you really want is to integrate AAD. You can easily enable AAD authentication for your .NET web application. It uses OWIN middleware.

If you are using a aspnet or aspnetcore, you can get the necessary code needed to sign in your web application with your Azure AD tenant just by following steps.
Create the sample from the command line
Note that MSAL.NET is a token acquisition library (for services like MS Graph and such) that can optionally sign-in users as well. the sign-in code is present in the aspnet and aspnet core SDKs

Related

Credentials prompt for access to Azure management APIs

I've been using the Azure fluent management APIs (https://github.com/Azure/azure-libraries-for-net) with some success in .NET Core.
However, I want to prompt the user to enter some credentials for a Microsoft account. Those credentials would have access to one or more Azure tenants / subscriptions, so I'd like to be able to use the result to browse and manage resources there.
This is something very close to what I would believe Azure Data Studio does: you can enter some Azure creds, and your resources will appear in the app.
I'm trying to understand the best approach for this. There seem to be a billion sites out there when you talk about Azure AD app registrations, but I haven't found a fruitful specific search query yet. I know I can register an app, get a client ID and client secret. I know I can set it to be usable by organisational accounts in the current tenant, or all tenants.
I can add the "Azure Service Management (delegated permissions : user_impersonation)" permission to my API permissions section for the app, but what's next?
If I use Microsoft.Identity.Client (as in https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-netcore-daemon), I run into some questions:
AcquireTokenForClientAsync doesn't prompt the user - I guess because it's getting a token for the app to act with its own permissions?
AcquireTokenOnBehalfOfAsync wants a JWT.. great! I'll pass the one I got from AcquireTokenForClientAsync! Nope, AADSTS70002: Error validating credentials. AADSTS500137: The token issuer doesn't match the api version: A version 1 token cannot be used with the v2 endpoint.
I don't know what scope I want. https://management.azure.com/user_impersonation is apparently invalid.. https://management.azure.com/.default works, but is that right? It's a guess, combo of the former and a .default suffix I found for Graph API scopes online. Any docs on this?
I ultimately get a JWT and tenant ID back. I can't find a way to use a JWT with the Fluent management APIs.. and my account (for instance) is associated with 3 tenants or 5 different tenants / directories - so how do I choose?
That's just what I've tried, the appropriate route might be a different one. In summary: I want a .NET Core Console app to request user credentials, and then get access to the Azure resources they have access to, in order to perform some resource management.
AcquireTokenForClientAsync doesn't prompt the user - I guess because it's getting a token for the app to act with its own permissions?
You are using the OAuth 2.0 client credentials grant to access web-hosted resources by using the identity of an application. This type of grant commonly is used for server-to-server interactions that must run in the background, without immediate interaction with a user .
AADSTS70002: Error validating credentials. AADSTS500137: The token issuer doesn't match the api version: A version 1 token cannot be used with the v2 endpoint.
Azure AD provide two service : Azure AD V1.0 and Azure AD V2.0 . Please refer to Comparing the Azure AD v2.0 endpoint with the v1.0 endpoint . You can't use v1 token to acquire v2's token in a on-behalf-of flow .
AcquireTokenOnBehalfOfAsync wants a JWT.. great! I'll pass the one I got from AcquireTokenForClientAsync
AS pointed above , That function is used to acquire an access token for this application (usually a Web API) from the authority configured in the application, in order to access another downstream protected Web API on behalf of a user using the OAuth 2.0 On-Behalf-Of flow. So you can't use app token which acquire using Client Credential flow .
https://management.azure.com/.default works, but is that right? It's a guess, combo of the former and a .default suffix I found for Graph API scopes online. Any docs on this?
You are using the Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow , when sending a POST request to the /token v2.0 endpoint ,the scope should be :
The value passed for the scope parameter in this request should be the resource identifier (Application ID URI) of the resource you want, affixed with the .default suffix. For the Microsoft Graph example, the value is https://graph.microsoft.com/.default. This value informs the v2.0 endpoint that of all the direct application permissions you have configured for your app, it should issue a token for the ones associated with the resource you want to use.
Please check the Get a tokensection in above document .
I ultimately get a JWT and tenant ID back. I can't find a way to use a JWT with the Fluent management APIs..
AFAIK , currently Azure AD V2.0 apps can use:
Its own API
Microsoft Outlook APIs
Microsoft Graph API
Azure AD V2.0 currently doesn't support Azure management APIs .
So you problem is you need to allows work and school accounts from Azure AD and personal Microsoft accounts (MSA) which works with Azure AD V2.0 , but you can't use Azure management APIs . You can use Azure management APIs in Azure AD V1.0 but it allows only work and school accounts to sign in to your application , unless you invite Microsoft accounts as guest user in Azure AD V1.0 ,but you need to configure to point to the tenant-specific endpoint :https://login.microsoftonline.com/{TenantId_or_Name}). during authentication if you want to login with MSA in v1.0 apps.
Update:
You can use Code flow and azure ad v1.0 endpoint , user will be redirect to AAD's login page and enter their credential. Here is code sample for .net Core .
With Azure AD V1.0 endpoint , requests are sent to an endpoint that multiplexes across all Azure AD tenants: https://login.microsoftonline.com/common . When Azure AD receives a request on the /common endpoint, it signs the user in and, as a consequence, discovers which tenant the user is from. See document here . But in this scenerio ,you can only use work and school accounts(AAD) account to login .
The code sample in your link is using Azure Service Principal for Authentication , no interactive user login . You can use OpenID Connect Owin Middleware for authentication in .net Core applications as shown here .

Single Sign on - Multiple application azure AD B2C

I am trying to have two applications(app1 and app2) in Azure
AD B2C, which is configured for Web api and another application that is configured for mobile app.
I need my mobile app to talk to app1, get the access token, using the app1's application-id and scope. Then use the access token got from app1 to communicate with app2. I enabled SSO in tenant level in the policies but it still says "Authorization denied" for the access token provided.
How can I reuse the access token got from one application to be used in another application.
We have been trying to get through this limitation (or function as designed for security) of B2C AD from weeks.
However, Microsoft does not support it.
We did not want to display MS login page to mobile user on mobile login screen (UX gets compromised). But MS says there is no way possible to avoid it. See response from MS on support ticket.
For more information: Azure AD B2C: Requesting access tokens
You will also benefit reading authentication scenarios supported. We are after something similar to this what they call "Daemon or Server Application to Web API".
In this diagram, Server Application = to mobile application in our case. However you will notice that in this scenario it is assumed that the user is already authenticated (via interactive flow).
We tried to act smart, thinking we can write a Auth web API which mobile will hit to obtain token and then pass this token to our business logic API (secured by B2C AD). We obtained access and refresh token somehow, however the test web app (mobile app) when pass this access token to our business logic API, it fails to validate the token. B2C AD comes fighting for it. Our analysis is not yet complete.
However, I am certain what we are trying to accomplish is not supported in B2C AD.
Hope this helps (I would actually advise you to look for other solution). I will be happy if someone can suggest a way to solve this obvious business problem.

Manage user from Azure AD B2C using AD Graph API - secure access

We are building a Xamarin Native mobile apps and using Azure AD B2C for authenticating users using their social logins.
We decided use MSAL native library (Xamarin) for authenticating using B2C. And our mobile app required to manage(full access) the signed-in user profile. Since this feature isn't available in MSAL we have decided to go with ADAL for the time being. Followed the instruction provided in the link below and the sample works. But I started experimenting by deleting the API access provided in the application (created in b2c tenant) and the ran the application with "Get-user" parameter. And the application is still able to get the users from AD. Not sure how secure is this thing?
Then deleted the application key from the B2c tenant application and ran the console application sample. And received an error AADSTS70002: Error validating credentials. AADSTS50012: Invalid client secret is provided.
Trace ID: cef09957-06bf-462e-a0c3-4ed6bae11e00
Correlation ID: afab126d-8694-479a-8a21-c12eb7cb176c
https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet
Any Idea why this is happening. I would like to implement this on a xamarin.ios app and any guidance much appreciated.
The answer to this is very similar to the answer to your other question: Exception access Azure AD B2C using ADAL library for user management, which can be summarized as:
Azure AD B2C does not yet support delegated permissions to the Azure AD or Microsoft Graph. The correct way to work around this limitation at this time is to have your native client application call a web API (using MSAL) which would in turn call the Graph API (using ADAL). This web API is an API you build which has authorization logic to scope the user management operations.
Once user management in Azure AD B2C is supported via the Microsoft Graph, you won't need this API and will be able to use delegated permissions (vs application permissions using client credentials) to have your native client application talk directly to the Microsoft Graph. In the interim, you'll have to stand up your own Web API as per the guidance above.
UPDATE: the Azure AD v2.0 endpoint and Microsoft Graph API now support client credentials flow, so you can also use MSAL for your Microsoft Graph API calls. However if you need to call the Azure AD Graph, then you will still need to use ADAL.

Does Azure Active Directory B2C work with Oauth or Open ID?

I successfully implemented Azure Active Directory for user management/authentication/login in a web app, following this example:
Azure Sample AAD with Flask
I decided to try Azure Active Directory B2C because of its integration for the various social apps. However, I could not get the flask app to work using OAuth 2.0, since Azure AD B2C does not seem to be compatible with OAuth 2.0. I found some documentation that states Azure AD B2C requires Open ID Connect.
Could you please confirm whether Azure Active Directory B2C requires Open ID Connect, or whether it works with OAuth 2.0 as well?
Thanks
It is worth to not that Azure Active Directory B2C (AAD B2C) supports both OpenID Connect and OAuth 2.0 in that it uses these two protocols to exchange information and secure tokens. However, AAD B2C "extends" these protocols by introducing Policies to handle the user experience for Sign-up, Sign-in and general account management.
What does this mean? First of, it means that you cannot create your own sign-up/sign-in experience, you are restricted to redirecting the user to the right policy (which you to some extent can customize). You cannot create your own sign-up/-in UI for this and you are restricted to styling/branding the provided web-based UI for this.
So in order to Authenticate using AAD B2C you could follow this guide, it should be easy enough to adapt to Python. You simply redirect the user to the /authorize endpoint of the AAD B2C and then validate the JWT you receive
Azure AD B2C supports both OpenID Connect and OAuth 2.0 as noted in the official reference protocols documentation.
To be able to sign-in users with Azure AD B2C using OAuth 2.0 and Flask, you'll need to adapt the sample to follow the OAuth 2.0 approach used in this sample: An Android application with Azure AD B2C using OAuth. Key things you'll need to adapt:
You'll need to specify the B2C authorization and token endpoints: https://login.microsoftonline.com/tfp/TENANT_NAME/POLICY_NAME/oauth2/v2.0/authorize. Example from Android sample
You'll need to add your application/client ID as a scope. Example from Android sample
You won't be able to call the Graph's /me endpoint for token validation and to get user details. You'll need to validate the token and extract the claims from it yourself (ideally through a good JWT open source library since this isn't trivial, unfortunately I don't know any that I can recommend at this time).
EDIT
I've created a python sample for Azure AD B2C and used python-jose for token validation and claim retrieval. Check it out.
Based on the documentation here, Azure AD B2C supports both OpenID Connect and OAuth 2.0 protocols.
Azure Active Directory (Azure AD) B2C provides identity as a service
for your apps by supporting two industry standard protocols: OpenID
Connect and OAuth 2.0. The service is standards-compliant, but any two
implementations of these protocols can have subtle differences.

How to use Microsoft Authentication Library (MSAL) for automated tests

How do I use MSA or MSAL to test client code against both business and consumer test accounts in the same test suite without any user interaction? Windows Integrated Auth is not an option for this, and is not implemented in MSAL even if I was running on the domain.
For ADAL, there is this blog post, Using ADAL .NET to Authenticate Users via Username/Password, but my understanding is that this option is not encouraged and may be disabled in the future. Plus, I can't use this for consumer accounts.
The current MSAL preview only silent flows for user based auth all rely on the presence of cached tokens, previously obtained via interactive authentication.
Chances are that this will be the case for the next preview as well. The domain based integrated authentication will eventually be supported. However the current plan of record for username and password grant is that the Azure AD v2.0 endpoint will not support it.

Resources