renchan
renchan

Reputation: 519

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

I'm trying to implement authentication in my angularjs and web api SPA. I'm using cookie based authentication. Here is the code from LogIn controller -

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

If the user exist on the server(forms authentication) then I'm generating a cookie and passing it to response.

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

However I'm struggling to understand what should I do with this cookie, and how can I check this cookie when the user will login successfully? Cookie is HttpOnly so there is no way to check it with JS code, and as far as I know it's not a best way to do it.

So I have no idea how can we check if the user is logged in, when he visits the page the next time. Could someone please explain it to me?

Upvotes: 1

Views: 1773

Answers (1)

Ron Brogan
Ron Brogan

Reputation: 901

Cookie validation should only happen on the server. On a basic level, you want to (on every request), check if there is an authentication cookie sent, and if so, validate it. If it's valid, the request may be fulfilled, if it's not valid, you reject the request. WebAPI has the [Authorize] attribute that you can decorate a controller with, which will validate the cookie for you.

There's a lot of documentation here

Upvotes: 1

Related Questions