[英]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.