首页 > 解决方案 > ASP.NET WebForms 在 Azure Active Directory 身份验证后读取 IDToken

问题描述

我有一个旧的webforms asp.net web 应用程序,基于Identity 2.0本地身份验证,我必须升级它以允许在公司的Azure Active Directory中注册的外部用户的身份验证。

我能够运行挑战并在他们在 Microsoft 上进行身份验证后在网页上取回用户,但我无法读取用户的任何信息。例如,我想知道他们的电子邮件,以便让他们进入我的应用程序或注册为新用户。我希望在令牌中包含这些信息,但是如何在服务器端访问它?

这是我的代码:

    public partial class Startup {
        public void ConfigureAuth(IAppBuilder app)
        {

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,User>(
                    validateInterval: TimeSpan.FromSeconds(120),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                    OnApplyRedirect = ctx =>
                    {
                       ctx.Response.Redirect(ctx.RedirectUri);                      
                    }
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);           

            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = "xxxxxxx-xxxx-xxxx-xxxxxxxxx",
                Authority = "https://login.windows.net/xxxxxxx-xxxx-xxxx-xxxxxxxxx",
                PostLogoutRedirectUri = "https://localhost:44364/testlogin.aspx",
                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
                }

            }
            );

        }

        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("~/TestLogin.aspx?ErrorMessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }

这是登录外部活动目录用户的调用:

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

最后在 TestLogin.aspx 页面中,我尝试读取有关已登录用户的信息:

if (Request.IsAuthenticated) //Always False!
{
    Label1.Text = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;
}

var userClaims = System.Security.Claims.ClaimsPrincipal.Current;
if (userClaims != null) //It's not null but there is no information about the email of the logged in user
{
    Label1.Text += userClaims?.FindFirst("name")?.Value; //It's empty
}

如何读取ID 令牌中活动目录返回的声明

更新

如果我删除 cookie 身份验证中的选项,Azure Active Directory 可以工作,但我无法再登录本地用户:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
     LoginPath = new PathString("/Account/Login"),
     Provider = new CookieAuthenticationProvider
      {
              OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,User>(
              validateInterval: TimeSpan.FromSeconds(120),
              regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
              OnApplyRedirect = ctx =>
              {
                  ctx.Response.Redirect(ctx.RedirectUri);                      
              }
        }
});

进入这个:

app.UseCookieAuthentication(new CookieAuthenticationOptions());

有没有办法让它们都起作用?

标签: c#asp.netazureazure-active-directoryopenid

解决方案


推荐阅读