使用ASP.Net Web表单获取AAD令牌 [英] Acquire AAD token using ASP.Net web forms

查看:121
本文介绍了使用ASP.Net Web表单获取AAD令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个现有的asp.net空Web应用程序.我们需要为此网站实施Azure Active Directory身份验证.我正在使用以下代码使用以下代码获取令牌.

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);
    }
}

此代码在调试时工作正常,打开Azure登录页面,我们获得访问令牌.但是在服务器上部署此应用程序时,无法打开azure登录页面,并且出现以下错误.

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.

当应用程序不在UserInteractive模式下运行时,显示模式对话框或窗体是无效操作.指定ServiceNotification或DefaultDesktopOnly样式以显示来自服务应用程序的通知.

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.

有人可以帮助我使用asp.net Web表单从azure活动目录中获取访问令牌吗?

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

推荐答案

如所示的错误消息,您无法从ASP.NET应用程序显示服务器上的对话框",这是没有意义的,因为您的用户正在使用浏览器,并且在服务器上看不到消息框.

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 .

在asp.net网络表单应用程序中,您可以将用户重定向到azure广告登录页面,以允许用户输入凭据,而不是显示对话框.请参考下面的代码示例,该示例使用身份验证代码流来获取访问令牌以访问资源:

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/");
            }
        }

请用您的替换网址,租户,客户端ID/客户端密钥替换.如果有帮助,请告诉我.

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

这篇关于使用ASP.Net Web表单获取AAD令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆