问题
I am having a difficult time understanding how to add custom claims when using Windows authentication in a .Net MVC app.
The challenge here is to populate the users's identity with custom claims from the database on login, so as to avoid making a db call every time I want to check a custom authorization attribute. But the use of Windows auth complicates things for me, as there's no login method in which to put the code that populates the roles.
Is there a method to override, or some other way to hook into the Windows auth login process?
回答1:
In .NET Core 2.0 you should use IClaimsTransformation.
For example:
public class CustomClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
((ClaimsIdentity)principal.Identity)
.AddClaim(new Claim(claim.Name, claim.Value)); //your values
return Task.FromResult(principal);
}
}
And add this code to Startup.cs
...
services.AddMvc();
services.AddScoped<IClaimsTransformation,CustomClaimsTransformer>(); // Add this
I don't know how to do this in ASP.NET MVC :/.
This is my first answer here :).
回答2:
The solution by Ondra worked for me, but just wanted to mention this article which recommends creating a new principal to avoid adding the same claim multiple times since await HttpContext.AuthenticateAsync();
could be called multiple times in the application which could trigger TransformAsync()
to run.
Reference: https://brockallen.com/2017/08/30/beware-in-asp-net-core-2-0-claims-transformation-might-run-multiple-times
来源:https://stackoverflow.com/questions/48434667/add-custom-claims-to-identity-when-using-windows-authentication