In this post, I will discuss yet another useful feature you can use Azure AD specially if you are building something that uses your Microsoft 365 Identity platform.
let's assume you're building an app that uses some of Microsoft 365 capability and integrates with it via the Graph API also you have your own custom APIs that connects to your custom application, you want to expose your custom application functionality via REST APIs to your app. The trick here is you want to protect your custom build APIs and hopefully manage to have a consistent experience.

In the past I've used IdentityServer to provide this functionality when I used to build fully custom solutions, but for this time I was thinking I was already using Azure AD to connect to MS Graph APIs, what if I can use it to protect my own custom endpoint.

The answer is pretty straight forward, you can easily protect your custom built API using Azure AD or event Azure B2C if you are  building a consumer type app.

  1. You'll need to create an Azure App registration by navigating to your portal.azure.com then going into Azure AD and create a new app.
  2. In the process of creating your new app you can choose whether it's for a single tenant vs. Multi-Tenant or it could be accessed via a consumer account (Microsoft Personal Accounts), in this case for simplicity I'll choose an single tenant option.
  3. After you create the new app, you will find an option called (Expose an API)
  4. In this screen you can define your API scopes and also ensure that your client application which you already have been using to access Microsoft Graph or any other Microsoft cloud endpoints is added as authorised client application.
  5. If you have done all of that you have completed the configuration part, now what you need to do to make your API protected by Azure AD is simple and very well explained in this Github repo https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2
Now your API will be protected by Azure AD, the other challenging part is to figure out scopes/Roles to provide a more mature endpoint authorization, as I mentioned before you can define scopes for your API in Azure AD and then you can use these scopes to protect either a whole controller or a specific action using the AuthorizeForScopes attribute

A very easy straight forward approach I found is to define Application Roles within Azure AD app registration and use Authorize Attribute with Roles. you can add users to specific application role

using the "Enterprise Applications" section of Azure AD and it could be either a direct assignment or your can assign a security group to a role if you have Azure AD P1 or P2 subscription.