I've implemented a claim-based authorization on ASP.NET Core 3.1, where I've stored authentication info through claims and I need to retrieve it after signing in.
I found a post on StackOverFlow and did what it said exactly; Now, I've faced another problem.
Problem
I try to get the ClaimsPrincipal
which I stored it while signing in. but once I try to retrieve it, it returns null; I read somewhere the ClaimsPrincipal
was not stored on the same thread. Then, how do I fix it?
Configuring the authentication and authorization in Startup.cs
like this:
services.AddAuthentication("Authn").AddCookie("Authn", options => {
options.Cookie.Name = "Authn";
options.LoginPath = "/Views/Account/SignIn";
});
services.AddAuthorization(options => {
options.AddPolicy("userSignInPolicy", p => p.RequireClaim("Role", "User"));
});
This is where authentication is done and ClaimsPrincipal
gets stored:
List<Claim> uclaims = new List<Claim>() {
new Claim("Role","User"),
new Claim("ID",p.User_id.ToString())
};
ClaimsIdentity userid = new ClaimsIdentity(uclaims, "Authn");
ClaimsPrincipal usercp = new ClaimsPrincipal(userid);
await HttpContext.SignInAsync("Authn", usercp);
Thread.CurrentPrincipal = usercp; //This is where ClaimsPrincipal is stored
return RedirectToAction("userDashboard");
And this is when I try to retrieve it:
public IActionResult userDashboard()
{
var id = (ClaimsIdentity)Thread.CurrentPrincipal; //id is returned null here :(
//rest of the action
}
Didn't find any similar issue on StackOverflow. Any help is appreciated.
CodePudding user response:
You don't have to store ClaimsPrincipal
in Thread.CurrentPrincipal
.
Inside your Controllers simply use this.User
to access the ClaimsPrincipal
.