c# - 使用 ASP.Net Web 表单获取 AAD token

标签 c# asp.net azure azure-active-directory

我们有一个现有的 ASP.NET 空 Web 应用程序。我们需要为此网站实现 Azure Active Directory 身份验证。我正在使用下面的代码来获取 token 。

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 登录页面,我们获得访问 token 。但是,当在服务器上部署此应用程序时, azure 登录页面无法打开,并且出现以下错误。

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 Active Directory 获取访问 token 吗?

最佳答案

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

在 ASP.NET Web 表单应用程序中,您可以将用户重定向到 Azure 广告登录页面,让用户输入凭据而不是显示对话框。请引用下面的代码示例,使用身份验证代码流程获取访问 token 来访问资源:

        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/客户端 key 替换为您的。如果有帮助,请告诉我。

关于c# - 使用 ASP.Net Web 表单获取 AAD token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43488511/

相关文章:

c# - dirinfor.EnumerateFiles -> 错误

asp.net - HttpContext.Current.Server 空

azure - az aks get-credentials 使用自定义 ssh key ?

java - 在 Java 中生成 SAS token 以下载 Azure 数据存储容器中的文件

c# - 修改nHibernate在nServiceBus中保存Saga数据的方式

c# - 为什么在VS2005中查找引用时文件需要 "Prepared"

.net - ASP.Net MVC 2 - 将所有输出合并到单个程序集中

asp.net - 在 azure 上转换 web.config

amazon-web-services - 用于基于命令行的 SAML2 SSO 的 Azure AD API(用于 AWS 联合登录)

c# - 将 Button 绑定(bind)到 ItemsControl 容器中的 RelayCommand