【问题标题】:Acquire AAD token using ASP.Net web forms使用 ASP.Net Web 表单获取 AAD 令牌
【发布时间】:2022-05-10 21:18:44
【问题描述】:

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

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

当应用程序未在 UserInteractive 模式下运行时显示模式对话框或表单不是有效操作。指定 ServiceNotification 或 DefaultDesktopOnly 样式以显示来自服务应用程序的通知。

有人可以帮助我使用 asp.net Web 表单从 azure Active Directory 获取访问令牌吗?

【问题讨论】:

  • 问题要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源对于 Stack 来说是题外话溢出,因为它们往往会吸引固执己见的答案和垃圾邮件。相反,请描述问题以及迄今为止为解决该问题所做的工作。在寻求帮助之前,请先尝试增强您的互联网搜索技能。
  • AAD Authentication 上的 Internet 搜索倾向于 asp.net mvc。但我需要使用 asp.net 网络表单进行 AAD 身份验证。我会请求一个示例或解决方法来使用 asp.net Web 表单对用户进行身份验证,并使用 AAD 获取令牌。我的问题是发布网站后无法打开 azure 登录页面。我在服务器中遇到上述错误,但在调试时它按预期工作。仅供参考,我当前的网站是使用 asp.net 空模板构建的,并且想为此添加 AAD 而不是重写为 aps.net mvc。
  • 托管在哪里? Azure 应用服务?
  • 不在 Azure 中。它托管在本地服务器 IIS 中。
  • 如果在 Azure 中托管它,则无需对 AAD 身份验证进行编程。使用应用服务“轻松验证”

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


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢。这工作得很好。再次感谢您。
  • @RanjithVushakola,如果有帮助,请将其标记为答案,以帮助遇到与您相同问题的其他人。
猜你喜欢
  • 2017-03-10
  • 1970-01-01
  • 2020-06-20
  • 2020-03-08
  • 2019-04-18
  • 2019-04-11
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多