1
votes

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?

1
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. Please try first to empower your Internet searching skills before asking for help.astaykov
Internet search on AAD Authentication are inclined towards asp.net mvc. But I need AAD authentication using asp.net web form. I would request a sample or workaround to authenticate a user using asp.net web form and acquire tokens using AAD. My problem is I am unable to open azure login page after publishing my site. I get above mention error in server but while debugging it is working as expected. FYI, my current website is build using asp.net empty template and would like to add AAD for this instead of rewriting into aps.net mvc.Ranjith Vushakola
Where is it hosted? Azure App Service?Sentinel
Not in Azure. Its is hosted in local server, IIS.Ranjith Vushakola
If you host it in Azure, you won't need to program the AAD auth. Use App Service "Easy Auth"Sentinel

1 Answers

2
votes

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.