Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Windows Azure Active Directory: Converting group memberships to role claims
using System.Linq;
using System.Security.Claims;
using System.Web.Mvc;
namespace WAADDemo {
/// <summary>
/// This class uses <see cref="GraphClient"/> to read the AD security groups in which a given
/// <see cref="ClaimsPrincipal"/> is a direct member and then converts the memberships to group
/// claims. The group claims are then used to authorize user actions with <see cref="AuthorizeAttribute"/>.
/// </summary>
public class GroupToRoleClaimAuthenticationManager : ClaimsAuthenticationManager {
/// <summary>
/// This is an arbitrary string identifying the claims issued by this class.
/// It exists to make it possible to distinguish those claims from other claims.
/// </summary>
private const string ClaimIssuerName = "waad-demo-usergroup-roleclaim";
/// <summary>
/// Augument <paramref name="incomingPrincipal"/> with claims obtained by converting
/// the user's direct security group memberships to role claims.
/// </summary>
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal) {
// In real life, you'll probably want to configure GraphClient in an IoC container
// and get it here by calling DependencyResolver.Current.GetService<GraphClient>()
// (unfortunately, the infrastructure doesn't support dependency injection for claims authentication managers)
// See for the implementation of GraphClient
var graphClient = new GraphClient("",
var userGroups = graphClient.GetUserGroups(incomingPrincipal.Identity.Name);
// Create one role claim for each group and add them to the claims collection
// After this, a user in the "Administrators" group will have an "Administrators" role claim
var roleClaims = userGroups.Select(g => new Claim(ClaimTypes.Role, g.DisplayName, null, ClaimIssuerName));
((ClaimsIdentity) incomingPrincipal.Identity).AddClaims(roleClaims);
return incomingPrincipal;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment