四处张望,但看起来我现在陷入困境。我在应用程序中使用Windows Active Directory进行身份验证。 为了授权,我使用索赔。在搜索了有限的核心文档之后,这就是我的代码。
Looked up everywhere but looks like I am stuck right now. I am using Windows Active Directory in my application for authentication. For authorization, I am using claims. After searching through the limited core documentation, this is how my code looks like.
Startup.cs
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddTransient<IPrincipal>( provider => provider.GetService<IHttpContextAccessor>().HttpContext.User); services.AddTransient<IClaimsTransformation, ClaimsTransformer>(); services.AddAuthentication(IISDefaults.AuthenticationScheme); }ClaimsTransformer.cs
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); } }但是问题是,每个每次从数据库加载请求和声明都是绝对错误的。有什么办法可以缓存它?我能够创建声明的cookie并将该cookie用于 4.0中的任何其他调用。我似乎找不到核心的方法。我检查的所有文档都不完整,或者不涵盖我的情况。我可以在应用程序中进一步声明文档在此处的说法: docs.microsoft/zh-cn/aspnet/core/security/authorization/claims
But the problem is, this code is called with every request and claims are loaded from the db every time which is absolutely wrong. Is there any way I can cache it? I was able to create a cookie of claims and use that cookie for any further calls in 4.0. I can't seem to find a way in the core. Any documentation I check, is incomplete or it does not cover my scenario. I am able to claims further in my application just how the documentation says here: docs.microsoft/en-us/aspnet/core/security/authorization/claims
但是没有提及缓存
有人在同一条船上吗?还是知道解决方法?
Anyone in the same boat? Or knows the way out of it?
推荐答案您可以注入 IMemoryCache 在您的 ClaimsTransformer 构造函数中提供服务。
You can inject the IMemoryCache service in your ClaimsTransformer constructor.
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; } }更多推荐
在.net core 2.0中缓存声明
发布评论