Ranjith Vushakola
Ranjith Vushakola

Reputation: 11

Acquire AAD token using ASP.Net web forms

We have an existing asp.net empty web application. We need to implement Azure Active Directory Authentication for this websites. I am using below code to Acquire tokens using below code.

protected async void btnLogin_Click(object sender, EventArgs e)
{            
    //AuthenticationResult result = null;
    try
    {
        string aadInstance = ConfigurationManager.AppSettings["aadInstance"];
        string tenant = ConfigurationManager.AppSettings["tenant"];
        string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
        Uri redirectURl = new Uri(ConfigurationManager.AppSettings["redirectURl"]);
        string clientID = ConfigurationManager.AppSettings["clientID"];
        string resouceID = ConfigurationManager.AppSettings["resouceID"];
        AuthenticationContext AuthContext;
        AuthContext = new AuthenticationContext(authority);
        var obj = await AuthContext.AcquireTokenAsync(resouceID, clientID, redirectURl, new PlatformParameters(PromptBehavior.Auto));
        if (obj.AccessToken != null)
        {
            AddSession(obj.UserInfo.GivenName);
            Response.Redirect("Home.aspx", false);
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

This code works fine while debugging, opens Azure login page and we get access token. But when deploying this application on server, azure login page doesn't open and I get following error.

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

Can someone help me in achieving access tokens from azure active directory using asp.net web form?

Upvotes: 1

Views: 5431

Answers (1)

Nan Yu
Nan Yu

Reputation: 27588

As the error message shown , you can't show dialog box ON SERVER from ASP.NET application, it makes no sense since your user is using browser and it can't see message boxes on server .

In asp.net web forms application , you could redirect user to the azure ad login page to let user input credentials instead of show dialog box . Please refer to below code sample which using authentication code flow to acquire access token to access the resource :

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["code"] != null)
            {
                var accesstoken = AcquireTokenWithResource(resource: "https://graph.microsoft.com/");

                Response.Write(accesstoken);
            }
        }


        protected void Button2_Click(object sender, EventArgs e)
        {
            GetAuthorizationCode();
        }

        public void GetAuthorizationCode()
        {
            JObject response = new JObject();

            var parameters = new Dictionary<string, string>
                {
                    { "response_type", "code" },
                    { "client_id", "clientid" },
                    { "redirect_uri", "http://localhost:8099/WebForm1.aspx" },
                    { "prompt", "login"},
                    { "scope", "openid"}
                };

            var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters));

            Response.Redirect(requestUrl);

        }
        public string AcquireTokenWithResource(string resource)
        {
            var code = Request.Params["code"];
            AuthenticationContext ac =
        new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", "tenantID"
                                  ));
            ClientCredential clcred =
                new ClientCredential("clientID", "clientSecret");
            var token =
                ac.AcquireTokenByAuthorizationCodeAsync(code,
                           new Uri("http://localhost:8099/WebForm1.aspx"), clcred,resource).Result.AccessToken;

            return token;
        }
        private string BuildQueryString(IDictionary<string, string> parameters)
        {
            var list = new List<string>();

            foreach (var parameter in parameters)
            {
                list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
            }

            return string.Join("&", list);
        }

        protected string EndPointUrl
        {
            get
            {
                return string.Format("{0}/{1}/{2}", "https://login.microsoftonline.com", "tenantID", @"oauth2/");
            }
        }

Please replace the redirect url ,tenant, client ID/client Secret with yours .Please let me know if it helps.

Upvotes: 2

Related Questions