I have propperly implemented a JWT authentication with my Asp.Net Web API. However, I am unsure how to use it together with my MVC application. Let me explain to you how I did it before. Once the user logged in, I saved the user inside a session.
// Add user to session
Session["User"] = MyUser;
And inside my view I did accesed it like this:
@{
var user = (User)Session["User"];
}
<h2>Welcome</h2>
<h4>@user.FirstName @user.LastName</h4>
Now I changed it saving a JWT token in a cookie once the user logged in like this:
HttpCookie UserCookie = new HttpCookie("UserCookie");
UserCookie.Value = JWTToken;
UserCookie.Expires = DateTime.Now.AddHours(24);
My JWT token has several claims which I want to access in my views like I did before with the session. How is that possible? Would someone suggest a different way?
you can access them in your controller like that
var claimsPrincipal= (ClaimsPrincipal)Thread.CurrentPrincipal;
// Get the claims values
string value = claimsPrincipal.Claims.Where(c => c.Type == "your key").Select(c => c.Value).SingleOrDefault();
then pass them to your view
don't forget to update your using
using System.Security.Claims;
using System.Threading;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.