問題描述
我在 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模板網!