How to manage user sign in and sign up processes in web API - azure

I have a web api as backend and a mobile app that users can sign up and sign in and call web api(protected) methods to post and get some data from user. I am using Azure AD B2C to authorize and authenticate users with policies. After a user has sign up or sign in, mobile side has an access token and use this token in request to web api.
But in my scenario, mobile side will send username to web api and I will use microsoft graph api to create user with username and default password.(First request is without user token because there is no a user at this time or can be special token that both sides know.) After I created user in server-side I want to get access token using objectId that came response from create request or I want to know how to get access token.
When I have token, I will send this token to mobile and then mobile send requests to web api using access token that come from server.
I wonder this scenario is possible and can be implemented.

Architecturally, If i understand correctly You want to protect your Mobile app and web api using Azure AD B2C which is clearly possible.
You need to do the following:
Create a AD B2C tenant.
Configure a sign-up or sign-in policy
Use the steps in the Azure AD B2C documentation to create a sign-up or sign-in policy. Name the policy SiUpIn. Use the example values provided in the documentation for Identity providers, Sign-up attributes, and Application claims. Using the Run now button to test the policy as described in the documentation is optional.
Register the API in Azure AD B2C
In the newly created Azure AD B2C tenant, register your API using the steps in the documentation under the Register a web API section.
After the API is registered, the list of apps and APIs in the tenant is displayed. Select the API that was previously registered. Select the Copy icon to the right of the Application ID field to copy it to the clipboard. Select Published scopes and verify the default user_impersonation scope is present.
After adding authentication to your web api , you can test it using Postman.For that you have to register postamn under your B2C tenant.
Since Postman simulates a web app that obtains tokens from the Azure AD B2C tenant, it must be registered in the tenant as a web app. Register Postman using the steps in the documentation under the Register a web app section. Stop at the Create a web app client secret section.
The newly registered web app needs permission to access the web API on the user's behalf.
Select Postman in the list of apps and then select API access from the menu on the left.
Select + Add.
In the Select API dropdown, select the name of the web API.
In the Select Scopes dropdown, ensure all scopes are selected.
Select Ok.
For calling a web api you need to get the bearer token before calling actual web api request.
To make an authenticated request to the web API, a bearer token is required. Postman makes it easy to sign in to the Azure AD B2C tenant and obtain a token. Taking postman as an sample tool.
- On the Authorization tab, in the TYPE dropdown, select OAuth 2.0. In the Add authorization data to dropdown, select Request Headers. Select Get New Access Token.
- Complete the GET NEW ACCESS TOKEN dialog as follows:
- Select the Request Token button.
- Postman opens a new window containing the Azure AD B2C tenant's sign-in dialog. Sign in with an existing account (if one was created testing the policies) or select Sign up now to create a new account. The Forgot your password? link is used to reset a forgotten password.
- After successfully signing in, the window closes and the MANAGE ACCESS TOKENS dialog appears. Scroll down to the bottom and select the Use Token button.
- Now you can test your Web Api with the token, also if you want to save suer information before that you can do that. Also it's the Signup Policies job is to create a user for your when you hit a request.
Hope it helps , Please let me know if you need any help.

Related

What is the flow of Azure AD based authentication in a project having SPA and web api?

I have a front end SPA (single page application) and back end api.
Each event in the SPA (like button click) invokes the respective api endpoint, and displays the result in the SPA.
I want to implement Azure AD based authentication so that only my Azure Tenant users are able to use the SPA/api.
Is the following flow correct approach to implementing such a feature:
User opens the SPA
User clicks on login button which opens Microsoft login popup
User enters Microsoft credentials in the popup, and if credentials are correct then user gets the JWT token
For every subsequent api request, the JWT token is placed in the bearer header
The endpoint validates the JWT token using Azure public key and rejects the request if token is missing or validation fails.
Is this flow correct and what is such a flow called?
There are several implementation steps that needs to be performed before you will have the flow that you have described:
User flow needs to be configured (Azure AD) - e.g. selfsignup allowed?
Backend and frontend applications needs to be registered (Azure AD)
Permissions and scopes needs to be added (Azure AD)
Backend API needs to be configured (e.g. API management) in order to validate the JWT token
I highly recommend to configure one of the Azure sample implementations end2end to get and idea of all the needed tasks: https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-spa-app
The steps you outlined are correct.
An OAuth 2.0 "flow" outlines the steps to acquire a token from an Identity Provider (IdP). Since you are using a SPA, there are some restrictions on which flows you can use. A SPA can't act as a "Confidential Client" which is required for some flows. (Basically - the Client Secret required for the other flows would be visible in the browser network trace, so it's not "confidential".) The "Implicit Flow" used to be recommended for SPAs but it's less secure, so now the "Authorization code flow (with PKCE)" is recommended. Steps 2 & 3 in the question above are when you are executing the flow to acquire a token.
The authentication flow doesn't really address how you save and send the token to the API (#4 in the question), but the Microsoft Authentication Library (MSAL) helps with that - More information here - https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-overview
In Azure AD, you'll want 2 App Registrations - one for your SPA and one for your API. The API App Registration will need to "Expose an API" which really means to define a scope. Your SPA App Registration will need to Add an "API Permission" to the scope you defined from your API App Registration. (It will show up in My APIs.) This relationship is how #5 in the question is enforced.
Many of the steps for setting up authentication in Azure AD and Azure B2C are similar but Azure AD is designed for authenticating users that are part of your organization. Azure B2C allows you to build a set of users that aren't members of a particular Azure AD organization.

User-Consent screen not showing when using Postman and .Net 6 Web Api

So I am writing a .NET 6 Core Web Api using Azure AD as authentication for the API.
Now when using Graph API as example, you need to setup Graph API scopes in the App Registration. Lets use a delegated "user.read" permission for this example.
I use Postman to receive the access token for the application by authenticating as an user against Azure AD for the API. I would expect to receive a consent-screen so I can consent to the usage of "user.read". This does not happen though.. I get logged in and receive a valid access token. In the Backend though, it will throw an error because the user / admin did not consent to the application.
How do I get around this? Why don't I get asked to consent the permissions set up in the app registration? Neither in Postman, nor in a Swagger oAuth Flow..
My current workaround for this is to use a React application and sign in over the frontend application. Using the frontend application, I get asked to consent to the permissions. After consenting, I can use postman without getting the "user didn't consent" - error.
Any ideas? What did I miss?
Let's focus on the user-consent page first. When we created an azure ad app then add api permission for it, then use this azure ad app to make your .net 6 app/react app integrate azure ad to use azure authentication, and we go to the microsoft sign in page and successfully sign in, we will see a dialog which indicating that this app require you to consent a list of permissions. The permissions are correspond to the api permissions you set for the aad app. After consent once, then it won't ask you to consent again when sign in next time.
This consent only happened when users are signed in. Let's go back to the flows used to generate access token in Azure AD. Since you used delegate permission, then you may used the recommend Auth code flow(Another flow called ROPC flow can also generate delegate access token but not recommended). When we used auth code flow, we need to sign in first, the login url should look like this:
https://login.microsoftonline.com/tenant.onmicrosoft.com/oauth2/v2.0/authorize?client_id=azure_ad_app_id
&response_type=code
&redirect_uri=http://localhost/myapp/
&response_mode=query
&scope=user.read
&state=12345
We need to use it to get the auth code, then we can use the code to generate access token, per my test, I created a new azure ad app and when I directly hit this url in the browser and sign in, it still required me to give the consent. So I'm afraid the reason why you didn't see the dialog when test in post man is that you've consent it when test in react app, or you don't use auth code flow.

Does Azure B2C provide REST API for login?

I have one application integrated with Azure B2C directory. Our problem is, login page is redirecting to Azure B2C portal (Own custom page) for authenticate or Authorize users and then revert back to the original website.
I need to open popup with my own website login design and at the backend, I am able to call Azure B2C REST api to validate users.
How I can create REST API for Login in Azure B2C portal?
Let me know if you have any information about the same.
As juunas said in the comment, you could use resource owner password credentials(ROPC) flow to validate users at the backend. You could call the API with the POST request at the end. Note: ROPC supports local accounts only.
Try to create resource owner user flow first.
You need to replace the username and password with the user's to be verified.
POST https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/B2C_1A_<ROPC_Auth name of the flow>/oauth2/v2.0/token
username=<username>
&password=<password>
&grant_type=password
&scope=openid <application-id> offline_access
&client_id=<application-id>
&response_type=token+id_token

Configure Postman to Test Get New Access Token from Azure AD B2C

I am following instructions provided by Microsoft to set up Postman for testing an Azure AD B2C secured Wep API:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/azure-ad-b2c-webapi?view=aspnetcore-3.0
https://learn.microsoft.com/en-us/azure/active-directory-b2c/tutorial-register-applications?tabs=applications#register-a-web-application
Under the section Use Postman to get a token and test the API, I get to Step 4 where the documentation states:
Postman opens a new window containing the Azure AD B2C tenant's
sign-in dialog. Sign in with an existing account (if one was created
testing the policies) or select Sign up now to create a new account.
The Forgot your password? link is used to reset a forgotten password.
This does not happen.
I am using the Implicit Grant Type and my Auth URL appears as follows:
https://<myDomain>.b2clogin.com/<myDomain>.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_SIGNUP_SIGNIN&client_id=d4d84f32-1e57-4daf-b010-399bb2614e0d&nonce=defaultNonce&redirect_uri=https%3A%2F%2Fjwt.ms&scope=openid&response_type=id_token&prompt=login
Scope is set to the following value:
https://<myDomain>.onmicrosoft.com/postman/user_impersonation openid offline_access
When I press the Postman Request Token button, the SignIn / SignUp User Flow (Policy) is interrupted with the following Error dialog stating:
Sorry, but we're having trouble signing you in. We track these errors
automatically, but if the problem persists feel free to contact us. In
the meantime, please try again.
Correlation ID: c1b01e2d-84ce-446e-a9c2-f3a8617eb9f2
Timestamp: 2019-11-21 20:03:31Z
AADB2C90018: The client id 'd4d84f32-1e57-4daf-b010-399bb2614e0d,d4d84f32-1e57-4daf-b010-399bb2614e0d' specified in the request is not registered in tenant '<myDomain>.onmicrosoft.com'.
Taking this client ID is not registered error on face value, the problem would appear related to improper registration of the Application (Client) within Azure AD B2C.
However, I am able to successfully run this SignIn / SignUp User Flow from within Azure AD B2C; and to successfully register new Users using that Policy.
To be clear, my ASP.Net Core Web API is not being run at this stage. I am simply trying to configure Postman to request a New Access Token from Azure AD B2C.
I have tested the document you provided and it works fine for me.
Based on your error message, it seems that you put your client id twice in the Client ID.
AADB2C90018: The client id
'd4d84f32-1e57-4daf-b010-399bb2614e0d,d4d84f32-1e57-4daf-b010-399bb2614e0d'
specified in the request is not registered in tenant
'.onmicrosoft.com'.
Please check it.

ID Token Validation in Azure B2C

I am very new to Azure B2C and trying to explore the options available to manage the identities in B2C. I have registered web application and also created required custom policy in B2C tenant. When I am trying to run the workflow from Azure B2C portal, I am able to redirect to registered application with IdToken and also able to view the ID token information in https://jwt.io
Below are some of the question which requires clarification
Suppose I have hyperlink in my web application(Asp.Net web form) which redirects the user into Azure B2C. On successful signin in Azure B2C, how to validate ,process ID Token and fetch the user information in web application. I have seen code samples related to button click event.
How to refresh the token in the above case.
The easiest way is to use the MSAL library on the client side.
This does all this for you.
You get back an id_token and an access token.
Only an access token can be refreshed.

Resources