我有一个应用程序,以前使用了FormsAuthentication
,一段时间以前我将其切换到使用WindowsIdentityFramework
中的IdentityModel
,以便我可以从基于声明的身份验证中受益,但它使用和实现都相当丑陋。所以现在我正在研究OwinAuthentication
。
我正在研究OwinAuthentication
和Asp.Net Identity
框架。但是目前Asp.Net Identity
框架的唯一实现使用EntityModel
,而我正在使用nHibernate
。因此,现在我希望尝试绕过Asp.Net Identity
,直接使用Owin Authentication
。最后我通过参考《如何忽略Identity Framework的魔法,并只使用OWIN auth中间件获取我需要的声明?》中的建议成功实现了登录,但是现在保存声明的cookie变得非常大。当我使用IdentityModel
时,我能够使用服务器端缓存机制在服务器上缓存声明,并且cookie只保留了缓存信息的简单令牌。在OwinAuthentication
中是否有类似的功能,还是我需要自己实现?
我预计会有以下情况之一...
- cookie保持为3KB,哦,它有点大。
- 启用类似于
IdentityModel
的Owin
中的SessionCaching功能,这是我不知道的。 - 编写自己的实现来缓存导致cookie膨胀的信息,并查看是否可以在应用程序启动时将其连接到配置
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),
});
}
}
更新 我使用Hongye提供的信息成功实现了期望的效果,并得出以下逻辑…
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);
}
}
System.Security.Claims.Claim
吗?获取用户 ID 扩展的代码是什么? - Kiquenet