我有一个曾经使用过的应用程序,FormsAuthentication
不久前我将其切换为使用IdentityModel
fromWindowsIdentityFramework
以便我可以从基于声明的身份验证中受益,但是使用和实现起来相当难看。所以现在我在看OwinAuthentication
。
我在看OwinAuthentication
和Asp.Net Identity
框架。但是该Asp.Net Identity
框架目前唯一的实现使用EntityModel
并且我正在使用nHibernate
. 所以现在我想尝试绕过Asp.Net Identity
并直接使用Owin Authentication
。我终于能够使用“如何忽略身份框架魔术并仅使用 OWIN auth 中间件来获取我寻求的声明? ”中的提示获得有效登录,但现在我持有声明的 cookie 相当大。当我使用它时,IdentityModel
我能够使用服务器端缓存机制来缓存服务器上的声明,并且 cookie 只是为缓存信息保存了一个简单的令牌。中是否有类似的功能OwinAuthentication
,还是我必须自己实现?
我希望我会在其中一艘船上...
- cookie 保持为 3KB,哦,它有点大。
- 启用类似于我不知道
IdentityModel
的 SessionCaching的功能。Owin
- 编写我自己的实现来缓存导致 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), }); } }
更新 我能够使用宏业提供的信息获得预期的效果,我想出了以下逻辑......
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);
}
}