[英]Annotation authorize doesn't working ASP.NET CORE
我正在做一個 CRM 項目。 我需要限制客戶和工作人員訪問某些頁面。 我正在使用 CookieAuthentication 和 Authorize 屬性,但由於某種原因它不起作用。
在為用戶注冊聲明和 cookies 后,我試圖訪問此頁面“Master/Index”或“MasterController/Index”,不確定重定向哪個頁面是正確的,但無論如何我看到的不是頁面: If Master as ControllerRoute If MasterController作為控制器路由
我 100% 確定該用戶不僅已獲得授權,而且甚至擁有它的角色,因為 debagger 在任何情況下都會顯示它: Step After If Statement Step After If Statement
我的 MasterController 是:
public class MasterController : Controller
{
[Authorize]
public IActionResult Index()
{
return View();
}
}
這就是我在 HttpPost 頁面上發送表單后注冊用戶的方式:
private async Task RegisterNewUser(LoginModel login, string r)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, login.Login),
new Claim(ClaimTypes.Role, r)
};
ClaimsIdentity claimsIdentity = new(claims, "Cookies");
await ControllerContext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
}
只是為了向您展示我在我的 Program.cs 中添加了 auth:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Verification/Auth";
options.LogoutPath = "/Verification/Logout";
options.AccessDeniedPath = "/";
});
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
順便說一句,如果我評論 [Authorize] 則一切正常,但這不是我需要的。
您的中間件的順序不正確。 您需要將 UseAuthentication() 放在UseAuthorization()
UseAuthentication()
之前。
使用它的方式,每次它訪問授權中間件時,它都會意識到用戶未通過身份驗證,因此重定向。 它永遠不會超過那個,因為它只有在成功通過授權中間件后才會到達身份驗證中間件。 因此你有一個無限循環導致你的瀏覽器決定它有太多的重定向。
有關詳細信息,請參見此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.