Web API:如何正确登录用户?

时间:2017-05-17 11:21:13

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

当用户登录时,我需要记住他,因为只有登录的用户应该能够到达/ api / prenews(例如)。这就是我尝试这样做的方式。 (userName变量是一个字符串,如果登录成功,则存储当前用户名。)

IList<Claim> claimCollection = new List<Claim>
{
       new Claim("username",userName)
 };

ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection);
HttpContext.Current.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, claimsIdentity);

我实现了这样的PrenewsController.c:

    public class PrenewsController : ApiController
    {
        /*
        ...
        */
        public IHttpActionResult GetPrenews()
        {
            string currentUser = HttpContext.Current.GetOwinContext().Authentication.User.Claims.FirstOrDefault(k => k.Type == "username").Value;
            if(currentUser!=null)//the user is logged in
            {/*...*/}
            else //the user is not logged in
            {/*...*/}
        }
    }

HttpContext.Current.GetOwinContext().Authentication.User.Claims.FirstOrDefault(k => k.Type == "username")始终为空。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您应该能够从User.Identity属性获取用户名,无需将其添加到声明中,我猜您的声明为null,因为在您的示例中IsPersistent属性设置为false,尝试将其设置为true并且它应该可以正常工作

<强> EDITED

试试这个:

var user = userManager.Find(userName, password);
var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("usename", "johndoe"));
HttpContext.Current.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, userIdentity)

这种方法非常适合我..我希望它有所帮助。