【发布时间】:2015-10-08 18:22:00
【问题描述】:
我有一个 ASP.NET 身份库的自定义实现,使用 Dapper 而不是 Entity Framework,主要来自此处的教程:http://blog.markjohnson.io/exorcising-entity-framework-from-asp-net-identity/。
使用我的 AuthenticationManager 登录和注销用户一切正常。但是,一旦我在用户登录后重定向到任何地方,httpcontext 基本上是空的,并且用户不再经过身份验证。如果我也使用 [Authorize] 属性,那么用户会被自动声明为未经授权,并引发 401 错误。
这是我的 AccountController 的一部分:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(Login login, string redundant)
{
var master = new MasterModel();
if (ModelState.IsValid && (!string.IsNullOrEmpty(login.Email) && !string.IsNullOrEmpty(login.PasswordHash)))
{
var user = await Models.User.FetchUserByEmail(login.Email);
if (user != null)
{
await SignInAsync(user, true);
master.User = user; // User is now signed in - No problem
return RedirectToAction("Overview", "Account", master);
}
}
TempData["Message"] = "Your username or password was not recognised. Please try again.";
return View(master);
}
[HttpGet]
//[Authorize(Roles = "admin,subscriber")] // 403 when uncommented
public ActionResult Overview(MasterModel master = null)
{
// master is just a blank new MasterModel ??
if (!HttpContext.User.Identity.IsAuthenticated)
{
// User is always null/blank identity
TempData["Message"] = "Please log in to view this content";
return RedirectToAction("Login", "Account", master);
}
var userName = string.IsNullOrEmpty(HttpContext.User.Identity.Name)
? TempData["UserName"].ToString()
: HttpContext.User.Identity.Name;
var user = Models.User.FetchUserByEmail(userName).Result;
if (master == null) master = new MasterModel();
master.User = user;
return View(master);
}
我的 UserStore 实现了以下接口:
public class UserStore : IUserStore<User>, IUserPasswordStore<User>, IUserSecurityStampStore<User>, IQueryableUserStore<User>, IUserRoleStore<User>
我的 RoleStore 只是实现了IQueryableRoleStore<Role>
User和Role分别实现IUser和IRole
我错过了什么?
更新1: 这是 AuthenticatonManager 的一部分:
public IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(User user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
【问题讨论】:
-
您是否已将应用设置为使用 cookie 身份验证?
-
@WiktorZychla 是的。我已经用当前的 AuthenticationManager 和被调用的 SignInAsync() 方法更新了这个问题。作为参考,据我所知,SignIn 是成功的。
-
我的意思是
UseCookieAuthentication调用了IAppBuilder。SignIn可能只是不创建 cookie。您可以使用 Fiddler 等 http 调试器轻松验证它。 -
这就是我错过的!没有在 IAppBuilder 中设置它!谢谢@WiktorZychla
-
下次如果有人在评论中帮助您,请提及并让此人回答并接受此答案。 SO 的一部分乐趣不仅在于获得他人的帮助,还在于帮助他人获得积分 :)
标签: c# asp.net-mvc asp.net-identity