基于身份角色的授权不起作用

本文关键字:角色 授权 不起作用 身份 于身份 | 更新日期: 2023-09-27 18:03:39

我有一个自定义的ASP实现。. NET身份基础,使用Dapper而不是实体框架,主要来自这里的教程: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);
}

My UserStore实现以下接口:

public class UserStore : IUserStore<User>, IUserPasswordStore<User>, IUserSecurityStampStore<User>, IQueryableUserStore<User>, IUserRoleStore<User>

My RoleStore只是实现了IQueryableRoleStore<Role>

User和Role分别简单实现IUserIRole

我错过了什么?

Update1: 下面是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);
}

基于身份角色的授权不起作用

感谢@WiktorZychla指出答案。

事实证明,我遗漏了向IAppBuilder添加cookie认证的基本步骤。

OwinStartup.cs现在如何查找参考:

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
[assembly: OwinStartup(typeof(appNamespace.OwinStartup))]
namespace appNamespace
{
    public class OwinStartup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

希望这将拯救别人从撕裂他们的头发!