Skip to main content

Development

Securing Your Web API Using Azure Active Directory

Large or small, all companies need web security. And what better way to secure your ASP.NET Core Web API than using Azure Active Directory?

Given MVC-style apps are the dominant force in the market nowadays, the majority of documentation on the matter focuses here. That left me, desiring to create a loosely-coupled Web API instead of an MVC app, scouring Microsoft documentation, Stack Overflow questions, and GitHub examples to find answers.

Now that I have successfully completed the task, I would like to share the solution to all of you on a similar quest. I hope my guide helps speed up the process (and lets you look good in front of the boss).

Technologies Used

  1. Azure organization account
  2. JavaScript
  3. ASP.NET Core
  4. NPM or Yarn
  5. Adal.js

Prerequisites

  1. Install the languages listed above (besides Adal.js, we’ll do that later) and your choice of a package manager (NPM or Yarn- I use Yarn).
  2. Make sure you have an Azure account linked with an organization
  3. I will be using Visual Studio (for the API) and Visual Studio Code (for the client) – I recommend you use these as well.

Steps

If you just want to skip to the code, check out the sample project I created.

Create Web API structure

We will start with the API. This will all be done in Visual Studio.

  1. Create the Project
    1. Select File > Create New Project
    2. Choose ASP.NET Core Web Application
    3. Name your project and click “Create”
    4. Select “API”
    5. On the right-hand side under “Authentication” it says “No Authentication.” Click the option under this that says “Change”
    6. A window will pop up
      1. Select “Work or School Accounts”
      2. In “Domain” – this may be filled in with your organization’s address already. If not, fill it in with your organization’s “onmicrosoft” address (e.g. perficient.onmicrosoft.com)
    7. Configuration
      1. Open appsettings.json
        1. You will see a JSON object titled “AzureAd.” Replace it with the structure below- using the pre-existing Domain, TenantId, and ClientId values. If these do not exist, you can get them from your API’s App Registry. Leave Audience and Issuer blank for now.

          Example
      2. [Optional] Endpoint Testing
        1. Run your API using IIS Express
        2. Notice how the webpage at localhost:[your_port]/api/values gives a 401 error. This is because in Controller > ValuesController.cs, the “[Authorize]” attribute covers the entire class. This means that each endpoint defined here needs proper authorization to be accessed. If you remove the attribute and try again, the data will appear.

Secure using JWT and Azure AD

  1. JWT Setup
    1. Open Startup.cs
    2. In ConfigureServices(), you add this to your code:
      Example
  1. Secure your Endpoints
    1. Navigate to one of your controllers
    2. To require authorization to access your endpoints, we will use the “[Authorize]” attribute. To secure all endpoints in the file, place the attribute above the class declaration. To secure a single endpoint, place the attribute only above the method.
  2. Your turn
    1. Now it is your turn. Add your controllers, models, database access, and whatever else you need to complete your API. We will revisit this code at the end to fill in the empty values in appsettings.json.

Set up client structure

  1. Package Setup
    1. Create your project structure.
    2. I will be using Yarn for this example, but NPM has very similar commands (Yarn is built on NPM)
    3. Initialize Yarn inside your client’s parent folder using $ yarn init
  1. We will be using two packages- Adal.js and http-server. Install these:
    1. $ yarn add http-server
    2. $ yarn add adal-angular
      (Don’t worry about the angular part, this is used for vanilla JS as well)
  2. Your turn
    1. Now it is your turn to set up your client-side code (if you haven’t done so already). Feel free to write your CRUD requests already, we will only need to add one line to each of them after our next step.

Integrate Adal.js

  1. Login Setup
    1. Create a JavaScript file- this will be used as your login controller
    2. Add the following code:
      Example
      When run, this will setup and redirect you to the Microsoft login page.
    1. Now navigate to the Azure Portal and open your Client’s App Registration. Fill in the ClientId with your Application / Client ID. Fill in the Tenant with your Directory / Tenant ID.
    2. Don’t forget to add this script to your login page (before your other scripts)! It will run automatically on navigation to the page.
    3. You can call logout however you like, but it will not run on its own. After logging out, the page will (eventually) redirect to the page you specify in the window.config setting “postLogoutRedirectUri”
  1. Bearer Token Retrieval
    1. In the JavaScript file that contains your API requests, add the following code:
      Example
    2. The “token” variable stores the bearer token we will use in our request. If you are using XMLHttpRequest to make the request, you can add the token to the request header using: setRequestHeader(“Authorization”, `Bearer ${token}`)

Set up SSL

  1. Set up OpenSSL on your machine
    1. The guide I used
  2. Run the following command to generate your key and certificate (you may need to run your terminal as admin)
    $ openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
  3. Place key.pem and cert.pem in your client folder
  4. Now, when you go to run http-server, using the following flags:
    $ http-server -S -C cert.pem –o
  5. With your project running, copy the token we printed earlier from the console and save it for this coming step.

Azure App Registration

  1. Go to the Azure Portal and login using your organization’s domain
  2. Select “Azure Active Directory” and then “App Registrations” (on the left)
  3. You should see your API app already registered. If not, repeat the next step for your API app.
  4. Register your Client App
    1. Click “New Registration”
    2. Enter your chosen name (this can be changed later) and click “Register”
  5. API Settings
    1. Select your API app
    2. Authentication
      1. Select the “Authentication” tab
      2. Check the boxes “Access tokens” and “ID tokens”
      3. Save
    3. Manifest
      1. Select the “Manifest” tab
      2. Find “oauth2AllowIdTokenImplicitFlow” and “oauth2AllowImplicitFlow” – set these both to true
      3. Save
  6. Client Settings
    1. Select your client app
    2. Authentication
      1. Select the “Authentication” tab
      2. For your redirect URI, enter the page where you will be signing in
        1. This is found by looking at which page you are on when your Adal.js code calls login()
        2. If you get an error on the Microsoft login stating the reply URL doesn’t match what’s expected, decode the URL of that page. It should have the correct reply URL.
      3. For your logout URL, enter whichever page you would like to be redirected to after logout
      4. Save
    3. API permissions
      1. Select the “API Permissions” tab
      2. Click “Add a permission”
      3. Select the “My APIs” tab from the window that pops out
      4. Select your API app
      5. Click on “Delegated permissions” and “user_impersonation”
    4. Manifest
      1. Select the “Manifest” tab
      2. Find “oauth2AllowIdTokenImplicitFlow” and “oauth2AllowImplicitFlow” – set these both to true
      3. Save
  7. Updating the API configurations
    1. Open appsettings.json
      1. For TenantId, enter the Directory / Tenant Id from your API’s Azure App Registrations Overview
      2. For ClientID, enter the Application / Client Id from the same page
      3. Grab the bearer token that we saved earlier and paste this into the form at jwt.io.
      4. For Audience, Enter the value found under “aud” here.
      5. For Issuer, grab the base URL from “iss” (e.g. https://sts.windows.net/)
    2. [Optional] Open Properties > launchSettings.json
      1. Change the “launchUrl” values to be the endpoint data you want to see when launching IIS Express

Now you should be finished! Startup IIS Express and http-server (using the command from above to add SSL) and test it out. If you have any comments or concerns about my code or the steps to reproduce it, feel free to email me at josh.kostal@perficient.com

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Josh Kostal, Associate Technical Consultant

I am a recent college graduate who moved from Omaha to Atlanta to work at Perficient, where I started in May 2019. I enjoy working on APIs and microservices using .NET or Ruby on Rails, with an emphasis on security.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram