У меня есть старое webforms asp. net веб-приложение, основанное на 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 Token ?
ОБНОВЛЕНИЕ
Если я уберу опцию в кулинаре ie аутентификация, 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());
Есть ли способ заставить их обоих работать?