我有一个过go 使用FormsAuthentication
的应用程序,不久前我将它从WindowsIdentityFramework
改为使用IdentityModel
,这样我就可以从基于声明的身份验证中获益,但它的使用和实现相当难看.所以现在我看到的是OwinAuthentication
.
我看到的是OwinAuthentication
和Asp.Net Identity
框架.但是Asp.Net Identity
框架目前唯一的实现使用EntityModel
,而我使用的是nHibernate
.所以现在我想试着绕过Asp.Net Identity
,直接使用Owin Authentication
.我终于能够使用来自"How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek?"的提示获得一个工作登录,但现在我的cookie中包含索赔的内容相当大.当我使用IdentityModel
时,我能够使用服务器端缓存机制来缓存服务器上的声明,而cookie只为缓存的信息保存了一个简单的令牌.OwinAuthentication
中有没有类似的特性,或者我必须自己实现它?
我想我会在其中一艘船上.
- cookies 保持3KB,哦,它有点大.
- 启用一个类似于我不知道的
Owin
中IdentityModel
的SessionCaching的功能. - 编写我自己的实现来缓存导致cookieinflating 的信息,并查看在应用程序启动时配置
Owin
时是否可以将其连接起来. -
我做的都是错的,有一种方法我没有想到,或者我在
Owin
中误用了一些东西.public class OwinConfiguration { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", AuthenticationMode = AuthenticationMode.Active, CookieHttpOnly = true, CookieName = "Application", ExpireTimeSpan = TimeSpan.FromMinutes(30), LoginPath = "/Login", LogoutPath = "/Logout", ReturnUrlParameter="ReturnUrl", SlidingExpiration = true, Provider = new CookieAuthenticationProvider() { OnValidateIdentity = async context => { //handle custom caching here?? } } //CookieName = CookieAuthenticationDefaults.CookiePrefix + ExternalAuthentication.ExternalCookieName, //ExpireTimeSpan = TimeSpan.FromMinutes(5), }); } }
UPDATE
Provider = new CookieAuthenticationProvider()
{
OnValidateIdentity = async context =>
{
var userId = context.Identity.GetUserId(); //Just a simple extension method to get the ID using identity.FindFirst(x => x.Type == ClaimTypes.NameIdentifier) and account for possible NULLs
if (userId == null) return;
var cacheKey = "MyApplication_Claim_Roles_" + userId.ToString();
var cachedClaims = System.Web.HttpContext.Current.Cache[cacheKey] as IEnumerable<Claim>;
if (cachedClaims == null)
{
var securityService = DependencyResolver.Current.GetService<ISecurityService>(); //My own service to get the user's roles from the database
cachedClaims = securityService.GetRoles(context.Identity.Name).Select(role => new Claim(ClaimTypes.Role, role.RoleName));
System.Web.HttpContext.Current.Cache[cacheKey] = cachedClaims;
}
context.Identity.AddClaims(cachedClaims);
}
}