Authenticate Azure App Service with Azure AD Security Group

If you're developing Azure App Service i.e. ASP.NET MVC application and there is a requirement to authenticate current user against Azure AD Security Group you need to consider some steps:
In th Startup.cs as the part of UseOpenIdConnectAuthentication add/change Notifications

Notifications = new OpenIdConnectAuthenticationNotifications()
RedirectToIdentityProvider = (context) =>
string appBaseUrl = ConvertToSsl(context.Request.Scheme) + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl;
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
return Task.FromResult(0);

ConvertToSsl helps ensuring appBaseUrl starts with https protocol.

The Azure AD Application provided as a ClientId in OpenIdConnectAuthenticationOptions should have some adjustement in the manifest. Please refer to manifest guideline.
The change in the manifest is by adding / replacing line:
"groupMembershipClaims" : "SecurityGroup"

This is crutial to have desired authentication working properly.
Obviously, there is one action pending - how to auhtorize user. Let's commit we're going to use a filter approach by creating custom attribute class which inherits from AuthorizeAttribute, i.e.:

public class AuthorizeBySg: AuthorizeAttribute

and override AuthorizeCore function, i.e.:

protected override bool AuthorizeCore(HttpContextBase context)
if (!base.AuthorizeCore(context)) return false;
return ClaimsPrincipal.Current.Claims.Any(c => c.Type == "groups" && mygroupId == c.Value);

mygroupId is an object ID of restricted Azure AD Security Group.

Finally, decorate your Controller or methods in your Controller with newly created AuthorizeBySg attribute class.

Comments (0)

Skip to main content