【发布时间】:2022-11-20 10:07:40
【问题描述】:
Objective: Once logged in, be authorized to reroute to Contact page which is authorized with the Must Belong To HR Department policy. (Note: Using razor pages)
Expected: Log in, see the claims in user for HR department, have the policy requirements be read, allow the user access to the contact page.
Actual: Log in successfully, see claims in user for HR department, policy requirements not read or met or something, denied the user access to the contact page.
Program.cs file:
//Authorization
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("MustBelongToHRDepartment",
policy => policy.RequireClaim("Department", "HR"));
});
////RazorPage Options
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/contact", "MustBelongToHRDepartment");
});
Login page:
public async Task<IActionResult> OnPostAsync(User user)
{
var result = await _signInManager.PasswordSignInAsync(user.username,
user.password, user.rememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
//Create the security context
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.Email, "admin@mywebsite.com"),
new Claim("Department", "HR")
};
var identity = new ClaimsIdentity(claims, "MyCookieAuth");
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("MyCookieAuth", claimsPrincipal);
return RedirectToPage("contact");
}
else
{
return Page();
}
}
Is there anything I'm missing? Format? Silly error?
I have tried docs, YouTube videos, website, asking friends, and searching forums.
I have tried different methods of authorization and such, but nothing seems to work. This method I am using now should work according to documentation, but I know something is wrong with it.
Resources I have been using: This is a YouTube video on register and login docs docs
【问题讨论】:
-
The authorization on the page is implemented, the user is getting the claim, but the policy is not being implemented or read or something
-
Damn, 3 days. I thought I structured the question well.
标签: c# .net authorization asp.net-authorization