Implementing Forms authentication over async reque

2019-04-13 05:52发布

问题:

In an angular app with a .net web api backend, I'm trying to implement forms authentication over async requests.

Here is the relevant portion of my web.config...

<authentication mode="Forms">
  <forms loginUrl="/" cookieless="UseCookies" name=".TIMETRACK" requireSSL="false" timeout="30" protection="All" path="/TimeTrack" />
</authentication>

Here is my web api login method...

    [Route("Login")]
    public HttpResponseMessage Post(AppUser credentials)
    {
        var userTemplate = _authenticationProvider.GetUserByEmail(credentials.Email);

        var user = Mapper.Map<ClientUser>(credentials);
        if (userTemplate.HashCode == _cryptographyService.HashPassword(credentials.Password, userTemplate.Salt))
        {
            FormsAuthentication.SetAuthCookie(userTemplate.Email, false);
            user.IsAuthenticated = true;
        }
        return Request.CreateResponse(HttpStatusCode.OK, user);
    }

Here is my angular controller method making the call...

    $scope.authenticate = function () {
        if (validateAuthentication()) {
            $http.post('Authentication/Login', { Email: $scope.email, Password: $scope.password })
                .then(loginSuccess, loginFailure);
        }
    };

Analyzing the response with fiddler that is being sent back after the login I can see this...

Set-Cookie: .TIMETRACK=4D69EB09BD2B5B1444FBF07D1AB5EEE86DDEFD237AF451EF38EF6FD78E56E24DBD01369DEC865F81297114FF354BF3BC5C6099C3C5D1D89C001014BE071B4CB5A3059E28DBC7D6B25EE27A6FE2A31E278106D78E8FE080F73A6C8BBD3B6B83F12FAE9CD1AEE80629AA72B1DD16E0606D92D0C74F8388A932930C15D89178F92A; path=/TimeTrack; HttpOnly

So it seems like the cookie is being created. However, on subsequent requests to the server...

User.Identity.IsAuthenticated

Is always false. Nor am I seeing any sign of a cookie being sent back to the server.

Is there something special I need to do to pass that authentication cookie back up to the server?

For what it's worth, I've got this project out on GitHub. You can look at it here... https://github.com/JosephEricDavis/TimeTrack

Thanks for the help

回答1:

So it turns out that I had erroneously set the path attribute on the node in the web.config file. Once I removed the path attribute it started working as hoped.

For those like me who don't know what a path on a cookie is. I found this resource to be helpful.

Cookie path and its accessibility to subfolder pages