【问题标题】:ASP.NET application implement AAD SSO with SAMLASP.NET 应用程序使用 SAML 实现 AAD SSO
【发布时间】:2020-10-17 07:33:42
【问题描述】:

我正在尝试设置一个现有的 ASP.NET Web 应用程序,以使用 SAML 或 OAUTH 2.0 对 Azure Active Directory 帐户进行身份验证。教程仅向我展示了 MVC 中的示例代码,我想知道如何找到非 MVC 项目的示例。不支持吗?

【问题讨论】:

  • 您需要较早的教程。从 2014 年开始我的 wiktorzychla.com/2014/11/…
  • 另外,如果没有经过身份验证,我如何使访问网站上的任何页面时重定向到登录?

标签: asp.net azure active-directory saml


【解决方案1】:

我建议您使用以下非 mvc 使用旧版 asp.net 进行 oauth,

1.从Nuget包安装OWIN中间件NuGet包:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

2.右键单击项目的根文件夹: > 添加 > 新建项目... > OWIN 启动类。将其命名为 Startup.cs

3.将 OWIN 和 Microsoft.IdentityModel 引用添加到 Startup.cs:

using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;

4.用下面的代码替换Startup类:

public class Startup
{
    // The Client ID is used by the application to uniquely identify itself to Azure AD.
    string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

    // RedirectUri is the URL where the user will be redirected to after they sign in.
    string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

    // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
    static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

    // Authority is the URL for authority, composed by Azure Active Directory v2 endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
    string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

    /// <summary>
    /// Configure OWIN to use OpenIdConnect 
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.IdToken,
                // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter 
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false
                },
                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
        );
    }

    /// <summary>
    /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
    {
        context.HandleResponse();
        context.Response.Redirect("/?errormessage=" + context.Exception.Message);
        return Task.FromResult(0);
    }
}

Add the parameter value as below:

<add key="ClientId" value="Enter_the_Application_Id_here" />
<add key="redirectUri" value="Enter_the_Redirect_URL_here" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />

5.在aspx页面中添加登录和注销按钮。

    <asp:Button ID="Login" runat="server" Text="Button" OnClick="Login_Click" />
    <asp:Button ID="Loginout" runat="server" Text="Button"  OnClick="Loginout_Click"  />
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Code-behind:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                Label1.Text =  System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;
            }
        }

        protected void Login_Click(object sender, EventArgs e)
        {

            Context.GetOwinContext().Authentication.Challenge(
    new AuthenticationProperties { RedirectUri = "/" },
    OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }

        protected void Loginout_Click(object sender, EventArgs e)
        {
            Context.GetOwinContext().Authentication.SignOut(
               OpenIdConnectAuthenticationDefaults.AuthenticationType,
               CookieAuthenticationDefaults.AuthenticationType);
        }

【讨论】:

  • 哇非常全面的答案。我会试试这个,让你知道。
  • 重定向 URI,是我想在我的 Web 应用程序中将它们重定向到的内部页面吗?还是那是在 AD 中配置的?
  • 为了让它工作,我是否必须已经将它发布到我在 AD 中注册的域?如果我还没有准备好投入生产但我需要测试它是否正常工作怎么办?我想在 localhost 上测试
  • 这仍然允许我在不进行身份验证的情况下转到其他页面
  • MSFT 你帮了大忙,我们快到了。介意回答我上面的cmets吗?
【解决方案2】:

您可以在此document 上查看有关重定向 URL 及其限制的全部信息。

【讨论】:

  • 感谢您添加此内容。我看了看链接,很有意义。没有真正回答我的问题,但如果我有足够的声誉,我会投票。
猜你喜欢
  • 2016-03-08
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 2017-02-04
  • 1970-01-01
  • 2022-08-17
相关资源
最近更新 更多