tan*_*ush 4 .net c# asp.net claims-based-identity asp.net-core
到处都抬头,但看起来我现在被困住了。我在应用程序中使用Windows Active Directory进行身份验证。为了获得授权,我使用索赔。在搜索了有限的.net核心文档之后,这就是我的代码的样子。
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPrincipal>(
provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
Run Code Online (Sandbox Code Playgroud)
ClaimsTransformer.cs
class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
// call to database to get more claims based on user id ClaimsIdentity.Name
((ClaimsIdentity)principal.Identity).AddClaim(new Claim("now",DateTime.Now.ToString()));
return Task.FromResult(principal);
}
}
Run Code Online (Sandbox Code Playgroud)
但是问题是,每次请求都会调用此代码,并且每次都会从db加载声明,这是绝对错误的。有什么办法可以缓存它?我能够创建声明的cookie并将该cookie用于.net 4.0中的任何其他调用。我似乎找不到核心的方法。我检查的所有文档都不完整,或者不涵盖我的情况。我可以在应用程序中进一步声明文档在这里的说法:https : //docs.microsoft.com/zh-cn/aspnet/core/security/authorization/claims
但是没有提到有关缓存索赔的内容。
有人在同一条船上吗?还是知道出路?
您可以IMemoryCache在ClaimsTransformer构造函数中注入服务。
using Microsoft.Extensions.Caching.Memory;
public class ClaimsTransformer : IClaimsTransformation
{
private readonly IMemoryCache _cache;
public ClaimsTransformer(IMemoryCache cache)
{
_cache = cache;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var cacheKey = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (_cache.TryGetValue(cacheKey, out List<Claim> claims)
{
((ClaimsIdentity)principal.Identity).AddClaims(claims);
}
else
{
claims = new List<Claim>();
// call to database to get more claims based on user id ClaimsIdentity.Name
_cache.Set(cacheKey, claims);
}
return principal;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3735 次 |
| 最近记录: |