Azure AD group-based authorization with WebAPI and OWIN
I blogged about using Azure AD (AAD) groups as roles in an ASP.net MVC application a while ago. While speaking at Namesdays in Espoo, Finland last week, I presented briefly how the same approach can be applied in a WebAPI project. If you want to use AAD groups for adding role-based authorization to your APIs built with ASP.net WebAPI the story is similar but not identical.
Because in my case both solutions are based on the OWIN middleware, we can use the same approach of hooking up to OWIN “user authenticated” step for claims transformation - or maybe I should say enrichment.
Instead of using CookieAuthenticationOptions and CookieAuthenticationProvider, we can hook up to OAuthBearerAuthenticationProvider.OnValidateIdentity callback:
The membership verification and claims process is identical to the in in the previous post but here it is again
As previously, this code needs both Microsoft.Azure.ActiveDirectory.GraphClient and Microsoft.IdentityModel.Clients.ActiveDirectory nuget packages to work.
NOTE! The above code doesn’t cache group membership and it will check it on every request - even if the currently requested API method wouldn’t require user to be a member of (any) group. Also Azure AD access tokens for checking the membership is also cached in-memory as that’s the default in ADAL. Please see this post on more information about ADAL token caching.