1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm thinking of validating the cookie in the custom attribute like in this example - stackoverflow.com/questions/12672335/… However I'm not sure, instead of redirect, can I somehow pass the JSon object in custom attribute?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.