c# - 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());
有没有办法让它们都起作用?
解决方案
推荐阅读
- r - 坚持使用 R str_detect 需要正则表达式
- java - 制作一个返回数组中一位数字的数量的方法
- python - 转义 f 字符串中的单括号
- flutter - Flutter 驱动程序 - 在屏幕外的字段中输入文本
- android - Xamarin 将 EditText 从片段传递到片段
- hash - 查找计算元组流中项目平均值的哈希函数
- docker - VS Code:连接远程服务器中的 docker 容器
- html - 极简主义网站:标题 flexbox 文本垂直居中于 Chrome 桌面,但不是 Chrome 移动版。为什么?
- sql - 如何使 SQL 查询与 AWS Athena Presto 兼容
- c++ - 除非文本被复制和粘贴,否则作为 C++ 程序输入的文本文件将不起作用