我一直以Custom Authentication with MVC 3.0 by Brady Gaster为基础。
在大多数情况下,我的一切都在运作。但是我在登录后遇到了问题。这是与成功登录相关的登录代码:
SessionPersister.Email = model.Email;
FormsAuthentication.SetAuthCookie(model.Email, false); // added after failure, no impact
if (!string.IsNullOrEmpty(ReturnUrl) && Url.IsLocalUrl(ReturnUrl))
return Redirect(ReturnUrl);
return RedirectToAction("Index", "Home");
SessionPersister与Brady的版本完全相同,只是我将属性命名为Email。
在我的MVC控制器继承的自定义控制器中:
var email = SessionPersister.Email;
if (!String.IsNullOrEmpty(email))
{
var emp = Employee.GetEmployeeByEmail(email);
if (emp != null)
{
filterContext.HttpContext.User = new ManagerUser(Employee.GetEmployeeByEmail(email));
}
}
base.OnAuthorization(filterContext);
无论如何,问题是我可以成功登录,设置HttpContext.User并且IsAuthorized = true。但无论出于何种原因,当我RedirectToAction("索引"," Home")时,它会将我切换回登录屏幕。我该如何解决这个问题?
编辑:在Startup.Auth.cs中:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
添加到web.config,因为它以前是身份验证模式=无(在system.web中):
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
在看完之后我觉得它与OnValidateIdentity有关。要做一些挖掘。
答案 0 :(得分:0)
嗯,可能不是最有说服力的,但确实有解决方案。我创建了一个名为CustomAuthorizeAttribute的新AuthorizeAttribute,它处理如下:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionPersister.Email != null)
{
return Employee.GetEmployeeByEmail(SessionPersister.Email) != null;
}
return false;
}
}
而不是使用[Authorize]来装饰类,我使用[CustomAuthorize]
注意,这个系统只是一个&#34;如果你有登录,你就是好的&#34;事物的类型。如果有角色和不重要的角色,那么就需要更多的角色。