Custom IsInRole() เมื่อใช้ Cookie Middleware โดยไม่มี ASP.NET Identity

เพื่อรักษาความเข้ากันได้กับแอปพลิเคชันที่มีอยู่ ฉันวางแผนที่จะใช้ Cookie Middleware โดยไม่มี ASP.NET Identity ตามที่อธิบายไว้ในเอกสารประกอบ:

https://docs.asp.net/en/latest/security/authentication/cookie.html

ดูเหมือนว่าจะทำงานได้ตามที่คาดไว้ตราบใดที่ผู้ใช้เข้าสู่ระบบ แต่ฉันมีปัญหากับบทบาท โดยเฉพาะเมื่อใช้ [Authorize(Roles = "ADMIN")]

ในโค้ดด้านล่าง ฉันสามารถเรียก p.IsInRole("ADMIN") และเรียกใช้ MyClaimsPrincipal.IsInRole() ของฉันและคืนค่าเป็นจริง

สิ่งที่ใช้ไม่ได้คือแอตทริบิวต์ [Authorize(Roles = "ADMIN")] เนื่องจากท้ายที่สุดแล้วจะเรียก ClaimsPrincipal.IsInRole (ซึ่งส่งกลับค่า False) แทนที่จะเป็น MyClaimsPrincipal.IsInRole() (ซึ่งส่งกลับค่า True)

[Authorize(Roles = "ADMIN")]
public class MyAdminController : Controller
{
    public IActionResult Index()
    {
        var p = new MyClaimsPrincipal(ClaimsPrincipal.Current);

        bool isAdmin = p.IsInRole("ADMIN");

        return View();
    }
}
  1. เมื่อไม่ได้ใช้ Identity และใช้เฉพาะ Cookie Middleware ฉันสามารถใช้แอตทริบิวต์ [Authorize(Roles = "ADMIN")] ได้หรือไม่

  2. ยังไง? :-)

หากฉันต้องเดา ฉันใช้ p.IsInRole() ไม่ถูกต้อง ขณะนี้เมธอดนี้โหลดบทบาท แล้วส่งคืน True/False บางทีฉันอาจต้อง 'โหลด' บทบาทของฉันไปที่อื่นเพื่อให้ ClaimsPrincipal.IsInRole นั้นเพียงพอ ถ้าฉันใช้ Identity() ฉันคิดว่านี่จะเป็นการใช้งาน IUserRoleStore

คำตอบ 'ถ้าฉันต้องเดา' อื่น ๆ ของฉันคือที่ไหนสักแห่งใน startup.cs ฉันต้องแทนที่ ClaimsPrincipal ปัจจุบันด้วยอินสแตนซ์ของ MyClaimsPrincipal

ขอบคุณ!


person Robert Paulsen    schedule 03.05.2016    source แหล่งที่มา


คำตอบ (1)


คุณควรเพิ่มการอ้างสิทธิ์บทบาทเมื่อมีการสร้างคุกกี้

ใน startup.cs:

app.UseCookieAuthentication(options =>
{
     options.AuthenticationScheme = "MyCookieMiddlewareInstance";
     options.LoginPath = new PathString("/Account/Login/");
     options.AccessDeniedPath = new PathString("/Account/Forbidden/");
     options.AutomaticAuthenticate = true;
     options.AutomaticChallenge = true;
 });

และวิธีการโพสต์เข้าสู่ระบบอาจเป็นเช่นนี้ (ฉันคิดว่าคุณมีหน้าเข้าสู่ระบบที่กำหนดเอง):

[HttpPost]
public IActionResult Login(string userName, string password, string returnUrl)
{
     var user = _userService.GetUser(userName, password);// i assume that  _userService is injected
     if (user == null)
     {
          //return Error;
     }
     var claims = new List<Claim>()
     {
          new Claim(ClaimTypes.NameIdentifier, user.Id),
          new Claim(ClaimTypes.Name, user.GetFullName() ),
     };
     var identity = new ClaimsIdentity(claims, "Forms");
     identity.AddClaim(new Claim(ClaimTypes.Role, "ADMIN"));
     var principal = new ClaimsPrincipal(identity);

     HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);
     return Redirect(returnUrl);
}
person adem caglin    schedule 03.05.2016