[英]How to get logged in user information in ASP.NET
我正在研究ASP.NET项目,我试图捕获当前登录的用户信息,例如它的电子邮件地址。 如果使用cookie信息,很容易获得该电子邮件地址,但我不想要它。 因为那是安全性低的。 这是我尝试过的一些代码。
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
string email = identity.Claims.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
return Ok(email);
但我的回复是空的。 我认为这是因为Token信息和(ClaimPrincipal)Thread.CurrentPrincipal方法。 如何使用上述代码获取当前用户的信息。
您必须在用户进行身份验证后添加customized claims
,以便以后可以使用它。
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
以下是向电子邮件添加电子邮件的示例。
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
if (user != null)
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.Name));
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
如果没有令牌授权,则响应为NULL。 通过在请求标头中使用“授权”,我获得了电子邮件地址和已登录用户的名称。
以下是一些发送请求的代码。
var AuthData = JSON.parse(UserCustomService.getSessionStorage("Token")); //get Token
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"Authorization": "Bearer " + AuthData.access_token, // Bearer:type of Token
};
var GetUserInformation = function () {
var config = {
"async": true,
"crossDomain": true,
"url": ApiBaseUrl + "/GetUserInformation", // user defined route
"method": "GET",
"headers": headers
};
$.ajax(config).done(function (response) {
if (response) {
return ShowUserInformation(response);
} else return null;
});
}
var ShowUserInformation = function (response) {
$scope.User_EmailAddress = response.EmailAddress;
$scope.User_FirstName = response.FirstName;
$scope.User_LastName = response.LastName;
}
由于我认为安全性,令牌应位于所有请求标头中以获取和更新数据库中的当前用户信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.