We are working to integrate ASP.NET MVC web application with Azure PaaS. We are trying to get the User AD group from Azure Active directory but we have received the "Authorization Required" error.
DLL used: Microsoft.Azure.ActiveDirectory.GraphClient
Code used:
public async Task GetGroups(string objectId) {
IList groupMembership = new List();
try
{
if (objectId != null)
{
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
IUser user = await client.Users.GetByObjectId(objectId).ExecuteAsync();
var userFetcher = (IUserFetcher)user;
IPagedCollection<IDirectoryObject> pagedCollection = await userFetcher.MemberOf.ExecuteAsync();
List<string> groupsname = new List<string>();
do
{
List<IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
foreach (IDirectoryObject directoryObject in directoryObjects)
{
if (directoryObject is Group)
{
var group = directoryObject as Group;
groupMembership.Add(group);
groupsname.Add(group.DisplayName);
}
}
pagedCollection = await pagedCollection.GetNextPageAsync();
} while (pagedCollection != null);
string groupscsv = string.Join(",", groupsname.ToArray());
System.Web.HttpContext.Current.Session["Groups"] = groupscsv;
Response.Redirect("~/Index.aspx");
}
}
catch (Exception e)
{
if (Request.QueryString["reauth"] == "True")
{
//
// Send an OpenID Connect sign-in request to get a new set of tokens.
// If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
// The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
//
HttpContext.GetOwinContext()
.Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
//
// The user needs to re-authorize. Show them a message to that effect.
//
ViewBag.ErrorMessage = "AuthorizationRequired";
return View();
}
Kindly help us to fix this issue or provide any other sample source to get the user AD groups from Azure Active Directory.