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

时间:2015-07-19 15:22:22

标签: c# asp.net-mvc asp.net-identity

我有一个ASP.NET身份库的自定义实现,主要使用Dapper而不是实体框架来自这里的教程:http://blog.markjohnson.io/exorcising-entity-framework-from-asp-net-identity/

使用我的AuthenticationManager签入和退出用户一切都很好。但是,只要在登录用户后重定向到任何地方,httpcontext基本上就为null,并且不再对用户进行身份验证。如果我也使用[Authorize]属性,则会自动将用户声明为Unauthorized,从而引发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>

用户和角色只需分别实施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);
}

1 个答案:

答案 0 :(得分:0)

感谢@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")
            });

        }
    }
}

希望这可以帮助其他人免受撕裂的伤害!

相关问题