我在 Visual Studio 2017 中创建了一个默认的 ASP.NET Core 网站.我选择使用 Azure Active Directory 进行身份验证.我运行该站点,并且可以使用 Active Directory 中的帐户成功登录.
I have a default ASP.NET Core website created within Visual Studio 2017. I have chosen to authenticate using an Azure Active Directory. I run the site and can successfully login using an account in the Active Directory.
我可以检索 Active Directory 提供的声明信息,例如通过调用以下行,我得到了名称".
I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.
User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
我想为登录用户添加自定义声明 - CompanyId = 123456.我可以添加自定义声明,但它仅在设置声明的页面上可用.
I want to add a custom claim - CompanyId = 123456 for the logged in user. I'm able to add a custom claim however it is only available on the page where the claim is set.
Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);
我的理解是,我需要以某种方式更新由 Active Directory 颁发的令牌或在颁发令牌之前设置声明.我不确定该怎么做.
My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued. I'm unsure how to do this.
我怀疑这需要在 SignIn() 的 AccountController 中完成
I suspect this needs to be done in the AccountController at SignIn()
// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
return Challenge(
new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}
我已经阅读了许多关于此场景的文章和示例(包括 https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp)但是没有设法解决如何跨请求持久化声明.
I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.
我已经成功地使用 ASP.NET 身份作为身份验证提供程序来持久化自定义声明,但这似乎是因为自定义声明已保存到数据库中...
I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..
OnTokenValidated
为您提供了修改从传入令牌获得的 ClaimsIdentity
的机会,下面的代码用于您的参考:
OnTokenValidated
offers you the chance to modify the ClaimsIdentity
obtained from the incoming token , code below is for your reference :
private Task TokenValidated(TokenValidatedContext context)
{
Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
(context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(claim);
return Task.FromResult(0);
}
设置OpenIdConnectEvents
:
Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
OnTokenValidated = TokenValidated
}
然后在控制器中使用:
var companyId= User.Claims.FirstOrDefault(c => c.Type == "CompanyId")?.Value;
这篇关于ASP.NET Core 使用 Azure Active Directory 进行身份验证并跨请求保留自定义声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!