joeeames / MEANAppsFiles

Repository for my MEAN course on Pluralsight
117 stars 105 forks source link

Persisting Login Between Page Refresh #4

Closed ElliotPsyIT closed 9 years ago

ElliotPsyIT commented 10 years ago

Hi Joe - I'm working through your MEAN stack pluralsight course. It's excellent and I'm learning a ton.

I have a question about the bootstrapped user approach in the case where the server is re-started. It happened during your course when nodemon re-started the server even though you changed only client code. When the server was re-started, it left a desynchronized state with the client. There was an authenticated user on the client but no authenticated user on the server. You recognized this and then manually logged in again. But considering a live scenario, at that point routing on the client would have failed since the data requests to the server would be rejected on routes requiring an authenticated user.

Am I missing something in my representation of this scenario (the effect of re-starting the server where there is an active client)? If I've got this right, I wonder how you think about handling that case yet still want to bootstrap a user for login persistence across page refreshes?

Thanks again for your exceptional set of pluralsight courses!

Elliot

andreasgrimm commented 10 years ago

yes, great course!

maybe slightly off topic .. but what about authenticating without the use of cookies at all and instead use (JWT / bearer) access tokens that get set to be sent in the http header with every $http request?

e.g.

// when the client requests a token

var postData = $.param({
    grant_type: "password",
    username: username,
    password: password });

return $http({ 
    method: "POST", 
    url: that.url, 
    data: postData, 
    headers: { "Content-Type": "application/x-www-form-urlencoded" } }) 

.success(function (myTokenData) { 
    setToken(myTokenData);
});

function setToken(myTokenData) { 
    var sessionTokenValue = "Bearer " + myTokenData.access_token;

    $http.defaults.headers.common["Authorization"] = sessionTokenValue; 

    myStore.setItem(key, JSON.stringify(myTokenData)); //might be local storage
};

// when the client calls a service

this.getMyResource = function (id) {
    return $http({
      method: "GET", 
      url: myTools.baseUrl + "api/myresource/" + id
    }); 
};

Couldn't that simplify server side session handling .. or actually make it obsolete? The server had to authenticate each request though ... but server restarts wouldn't matter anymore.

Full client page reloads would trigger the app to initialize again. But during initialization the app could check myStore if an access token is available and call setToken again.

joeeames commented 9 years ago

Doing some housecleaning. Gonna close this issue. If the original issue persists, please post in the forums. For the second comment, great idea, I'll keep that in mind.