如何使用ASP.NET Web API+AngularJs基于cookie的身份验证来验证cookie

How to validate cookie with ASP.NET Web API + AngularJs cookie based authentication

本文关键字:cookie 身份验证 验证 基于 API+AngularJs 何使用 ASP NET Web      更新时间:2023-09-26

我正在尝试在angularjs和web api SPA中实现身份验证。我正在使用基于cookie的身份验证。这是登录控制器的代码-

if (ModelState.IsValid)
{
    if (_adMembershService.ValidateUser(model.Name, model.Password))
        {
            _formsAuthenticationService.SignIn(model.Name);    
            return Json(GetUserClientContext(model.Name));
        }    
    return Json("Incorrect Credentials");
}

如果用户存在于服务器上(表单身份验证),那么我将生成一个cookie并将其传递给响应。

public void SignIn(string email)
{
    //Part of the code is omitted    
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);            
    HttpContext.Current.Response.Cookies.Add(cookie);
}

然而,我很难理解我应该如何处理这个cookie,以及当用户成功登录时,我如何检查这个cookie?Cookie是HttpOnly,所以没有办法用JS代码检查它,而且据我所知,这不是最好的方法

所以我不知道当用户下次访问该页面时,我们如何检查他是否登录。有人能给我解释一下吗?

Cookie验证只应在服务器上进行。在基本层面上,你想(在每个请求中)检查是否发送了身份验证cookie,如果发送了,则验证它。如果它有效,则可以满足请求,如果它无效,则拒绝请求。WebAPI具有[Authorize]属性,您可以使用该属性装饰控制器,它将为您验证cookie。

这里有很多文档