簡體   English   中英

基於身份角色的授權不起作用

[英]Identity Role-based Authorization is not working

我有一個ASP.NET Identity基礎的自定義實現,使用Dapper而不是Entity Framework,主要來自此處的教程: http : //blog.markjohnson.io/exorcising-entity-framework-from-asp-net-identity/

使用我的AuthenticationManager登錄和注銷用戶,一切都很好。 但是,一旦我在登錄用戶后重定向到任何地方,httpcontext基本上為null,並且該用戶不再經過身份驗證。 如果我也使用[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>

用戶和角色分別簡單地實現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指出了答案。

原來,我沒有將Cookie身份驗證添加到IAppBuilder的基本步驟。

現在,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")
            });

        }
    }
}

希望這可以避免別人扯掉頭發!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM