我正在使用MVC 5.2并试图让Owin cookie中间件正常工作。
在我的登录控制器中,我执行以下操作:
public class LoginController
{
[AllowAnonymous]
public ActionResult Login(LoginViewModel loginViewModel)
{
//authenticate
....
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "abc"),
new Claim(ClaimTypes.Email, "abc@abc.com")
};
var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
//create the cookie - i thought
authenticationManager.SignIn(new AuthenticationProperties{IsPersistent = true}, id);
//redirect to protected action
return RedirectToAction("Index", "RoutingController");
}
[Authorize]
public class RoutingController : Controller
{
[HttpGet]
public ActionResult Index()
{
return this.View();
}
}
我连接了以下中间件
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login/Login"),
CookieSecure = CookieSecureOption.Always
});
}
以下是发生的事情
永久302循环...
我缺少什么?
由于
答案 0 :(得分:1)
//
// POST: /Account/Login
[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
要使Antiforgery工作,您还应将其添加到登录页面
@Html.AntiForgeryToken()