Azure Azure Active Directory B2C Azure AD B2C Blog Token Authentication Tutorial Web API 2 Web API Security

Secure ASP.NET Web API 2 using Azure AD B2C – Part 2

This is the second part of the tutorial which can cover Using Azure AD B2C tenant with ASP.NET Web API 2 and numerous entrance finish shoppers.

The supply code for this tutorial is obtainable on GitHub.

The Web API has been revealed on Azure App Providers, so be happy to attempt it out using the Base URL (https://aadb2cresourceapi.azurewebsites.net/)

Secure ASP.NET Web API 2 using Azure AD B2C

In the previous publish, we have now configured all the wanted insurance policies in our Azure AD B2C tenant and the Reply URLs. In this Submit, we’ll reconfigure the Web API we’ve got created in the previous publish so it relays on the Azure AD B2C IdP we created to secure it and our Web API will only accept and belief tokens issued by our Azure AD BC IdP.

So let’s begin implementing those modifications on the Web API.

Step 1: Configure Web API to use Azure AD B2C tenant IDs and Policies

Now we need to modify the online.config for our Web API by adding the under keys, so open Web.config and add the under AppSettings keys:

The values for these keys as the following:

  • “ida:AadInstance” value accommodates the metadata discovery endpoint for each coverage, this endpoint will probably be used internally by the middle-wares which we’ll add in the subsequent steps to validate the JWT tokens.
  • “ida:Tenant” value accommodates the URL for our Azure AD B2C tenant we now have already outlined within the previous submit.
  • “ida:ClientId” worth incorporates the App shopper Id we now have already registered with our Azure AD Bb2C tenant.
  • “ida:SignUpPolicyId” value incorporates the identify of the signup policy we already created.
  • “ida:SignInPolicyId” worth accommodates the identify of the Signin policy we already created.
  • “ida:UserProfilePolicyId” worth accommodates the identify of the Create profile coverage we already created.

Step 2: Add the additional NyGet packages to the Web API undertaking

Open NuGet Package deal Supervisor Console and set up/replace the under packages:

The packages we’ve got put in is answerable for configuring our API to make use of OAuth bearer token for cover as nicely we’ve added the packages which are answerable for validating, parsing and decoding JWT tokens.

I had to downgrade the package deal “System.IdentityModel.Tokens.Jwt” to the model “4.0.2.206221351” as the newer version of it showed breaking compatibility with other packages, I’ll control it and replace the publish accordingly if there are new updates.

lastly, we need to add manually using “Add reference” dialog a reference for the meeting “System.IdentityModel” v4, I’m unsure if there’s something incorrect with these NuGet packages which overlook to include this dependency by default. I will regulate this too and replace the submit if there is a change.

Step three: Configure the Startup class

Now we have to configure our API to depend on the Azure AD B2C IdP we already created, this is an important step in configuring the Web API to trust tokens issued by our Azure AD b2C IdP, our Web API will have the ability to eat solely JWT tokens issued by the trusted IdP and issued for a specific shopper only (The app we registered in the earlier publish “Bitoftech Demo App”).

To take action, open the “Startup” class for the Web API and exchange all of the content with under code, a lot of the modifications has been launched in technique “ConfigureOAuth” which I will describe what happen within the subsequent paragraph.

What we’ve got carried out is the next:

We’ve got configured our API to eat and belief JWT tokens issued by our IdP (“BitofTechDemo.onmicrosoft.com”) for a selected shopper (“bc348057-3c44-42fc-b4df-7ef14b926b78”) This shopper represents the app we already registered, as properly it should only accept JWT tokens for the three policies we already defined and named “B2C_1_signup”, “B2C_1_Signin”, and “B2C_1_Editprofile”. Another JWT tokens don’t meet these criteria can be rejected and 401 HTTP response is returned to the requestor.

Again to the Metadata Discovery Endpoint we mentioned earlier, this endpoint is auto generated by our IdP and it is extremely essential for our API to acquire the “Signing Tokens Keys” from it; to be able to validate the JWT signature and trust this JWT token and send a response to the requestor. This finish point is constructed at run time, for instance, the metadata endpoint for the “B2C_1_signin” can be as the comply with: https://login.microsoftonline.com/BitofTechDemo.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_signin feel free to click on the hyperlink and observe the info returned.

A nice trick right here that I’ve configured the “NameClaimType” of the “TokenValidationParameters” to make use of the claim named “objectidentifer” (“oid”) This can facilitate studying the distinctive consumer id for the authenticated consumer contained in the controllers, all we need to name now contained in the controller is: “User.Identity.Name” as an alternative of querying the claims collection each time.

The last thing we need to add to the “Startup” class is a brand new class named “OpenIdConnectCachingSecurityTokenProvider”, this class might be answerable for communicating with the “Metadata Discovery Endpoint” and problem HTTP requests to get the signing keys that our API will use to validate signatures from our IdP, those keys exists within the jwks_uri which may read from the invention endpoint. So as to add this class create a brand new class named “OpenIdConnectCachingSecurityTokenProvider” and paste the code under:

Step 4: Add protected controller for testing

Now we’ll add an (non-compulsory) class which reads all of the decoded claims in the JWT token and return them within the response, observe that we’ve got protected our controller by the [Authorize] attribute so solely valid JWT tokens shall be accepted to serve the request and return response, to do so add new controller named “ProtectedController” beneath folder Controllers and paste the code under:

We’ll check the controller within the next steps.

Step 5: Modify the “OrdersController” we created within the previous submit

Now we need to do a very little change on the “OrdersController” by including the [Authorize] attribute on the controller to guard it, as properly to read the unique authenticated consumer id from the declare and retailer it in Azure Table Storage as an alternative of the fastened worth we defined earlier within the previous publish. The change could be very simple and ought to be as the under snippet, a lot of the code is omitted so simply add/exchange the lacking elements as the under:

Step 6: Testing out the protected controllers

Last item we have to do here is to obtain a JWT token from out IdP by executing one of many insurance policies we have now outlined, then sending the JWT token in the Authorization header for one among out API endpoints, if all is sweet we should always access the API and return the protected assets.

To do that I have choose the policy Sign up from Azure AD B2C tenant and clicked on “Run now” button,  a brand new window will open and you provide a legitimate credentials, then a redirect will happen to the defined Reply URL and you may acquire the token manually by copying it, then you might want to ship the token to the top level “api/protected” or “api/orders” within the authorization header using the bearer scheme. The request will look because the under picture:

JWT Token Manually

GET Request to the “Api/orders” endpoint to listing all the orders assigned to the consumer with e mail “[email protected]

ProtectedOrdersRequest

Notice: This guide testing demonstrated right here is just for testing purposes, in the subsequent submit you will notice how we’ll add an MVC software which might be liable for executing the policies, get hold of JWT tokens, create the session for the authenticated users, and entry the protected API assets.

The Supply code for this tutorial is on the market on GitHub.

Comply with me on Twitter @tjoudeh