Quantcast
Channel: Azure Active Directory forum
Viewing all articles
Browse latest Browse all 16000

Adding Custom Application Level Roles in Azure Active Directory

$
0
0

Hi ,I faced an issue while adding roles to application.I am attaching the code below.What I am trying is to add role to AppRoles in ApplicationCollection through Graph Api.But am getting the exception as "

The context is already tracking the entity.

" Please reply immediately to this.If am doing wrong,Please say how to do that.

using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
using Microsoft.Owin.Security.OpenIdConnect;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebAppGraphAPI.Utils;

namespace WebAppGraphAPI.Controllers
{
    public class ApplicationRoleController : Controller
    {
        private static readonly string clientId = ConfigurationManager.AppSettings["ida:ClientId"];

        // GET: ApplicationRole
        public async Task<ActionResult> Index()
        {
            var roleList = new List<AppRole>();
            try
            {
                ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
                IPagedCollection<IApplication> pagedCollection = await client.Applications.Where(x => x.AppId == clientId).ExecuteAsync();

                if (pagedCollection != null)
                {
                    do
                    {
                        List<IApplication> applicationItemList = pagedCollection.CurrentPage.ToList();
                        foreach (IApplication application in applicationItemList)
                        {
                            roleList.Add((AppRole)application.AppRoles);
                        }
                        pagedCollection = await pagedCollection.GetNextPageAsync();
                    } while (pagedCollection != null && pagedCollection.MorePagesAvailable);
                }
            }
            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(roleList);
            }
            return View(roleList);
        }

        /// <summary>
        ///     Creates a view to for adding a new <see cref="User" /> to Graph.
        /// </summary>
        /// <returns>A view with the details to add a new <see cref="User" /> objects</returns>
        public ActionResult CreateRole()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> CreateRole(
            [Bind(
                Include ="DisplayName,Value"
                )] AppRole role)
        {
            ActiveDirectoryClient client = null;
            try
            {
                client = AuthenticationHelper.GetActiveDirectoryClient();
            }
            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();
            }

            try
            {
                IPagedCollection<IApplication> pagedCollection = await client.Applications.Where(x => x.AppId == clientId).ExecuteAsync();
                var appObject = pagedCollection.CurrentPage.ToList().FirstOrDefault();
                appObject.AppRoles.Add(role as AppRole);
                ////
                ////Am Getting Exception Here as "The context is already tracking the entity."....
                ////
                await client.Applications.AddApplicationAsync(appObject);
                return RedirectToAction("Index");
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return View();
            }
        }
    }
}


Please note that am trying to add roles and not groups.


Viewing all articles
Browse latest Browse all 16000

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>