如何在ASP.NET中获取登录的用户信息

时间:2019-04-23 15:43:27

标签: c# jquery asp.net-web-api

我正在研究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);

但是我得到的响应为NULL。我认为这是因为令牌信息和(ClaimPrincipal)Thread.CurrentPrincipal方法。 如何使用上述代码获取当前用户的信息。

2 个答案:

答案 0 :(得分:2)

您必须在用户验证后添加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);
}

答案 1 :(得分:2)

如果没有令牌授权,则响应为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;
    }

出于安全考虑,令牌应该位于所有请求标头中,以便获取和更新数据库中的当前用户信息。