Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Augmenting Mobile Service Response with Azure Active Directory Group Membership

In the previous post we saw how you can query Azure Active Directory after authenticating a Mobile Service client against Azure Active Directory. Now I’m going to use this knowledge to restrict access to data based on group membership. In this case the user has to belong to a group with the name “Inspectors”. One thing you’ll notice is that this process is quite slow, so we’ll have to look for a better way to enforce security, without having to query AAD with each service request. The full GetAll method is as follows:

public async Task<IQueryable<TEntity>> GetAll()
    var user = User as ServiceUser;
    var aadCreds = (await user.GetIdentitiesAsync()).OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();

    var token = this.ActionContext.Request.Headers.GetValues(Constants.RefreshTokenHeaderKey)

    var auth = new AuthenticationContext(Constants.ADAuthority, false);
    var newToken = await auth.AcquireTokenByRefreshTokenAsync(token,
        Constants.ADNativeClientApplicationClientId, "");

    var client = RetrieveActiveDirectoryClient(newToken.AccessToken);
    var grps = await client.Groups.ExecuteAsync();
    var moreGroups = grps.CurrentPage;
    while (moreGroups != null)
        foreach (var grp in grps.CurrentPage)
            if (grp.DisplayName == "Inspectors")
                if ((await client.IsMemberOfAsync(grp.ObjectId, aadCreds.ObjectId)) ?? false)
                    return Query();
            Debug.WriteLine(grp != null);
        if (grps.MorePagesAvailable)
            grps = await grps.GetNextPageAsync();
            moreGroups = grps.CurrentPage;

    return null;

Pingbacks and trackbacks (1)+

Comments are closed