简体   繁体   English

ASP.Net MVC访问JWT声明内部视图

[英]ASP.Net MVC access JWT claims inside view

I have propperly implemented a JWT authentication with my Asp.Net Web API. 我已经用我的Asp.Net Web API正确实现了JWT身份验证。 However, I am unsure how to use it together with my MVC application. 但是,我不确定如何将其与我的MVC应用程序一起使用。 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: 现在,我更改了它,一旦用户这样登录,就将JWT令牌保存在cookie中:

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. 我的JWT令牌具有多个声明,我希望像在会话之前一样在视图中访问它们。 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

using System.Security.Claims;
using System.Threading;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM