browser refresh - lost servicestack authentication session data

China☆狼群 提交于 2019-12-24 07:05:34

问题


I have an angular.js single page app that authenticates against a RESTful API (Servicestack). This all works fine. When the response from the authentication api is returned the username is stored on an Angular service and an isAuthenticated flag is set to true.

Any requests against an [Authenticate] attributed web service then returns data.

My issue is that when I refresh the browser my javascript angular objects are flushed and the fact the user authenticated is forgotten. Yet when I call the [Authenticate] attributed service they work correctly because the session is still live...

Apologies for the rather noob question but how does the browser pass the session to the web service when the javascript objects have been destroyed and recreated? How do I grab the same session on refresh and set my Angular service up with the username etc.?


回答1:


ServiceStack Authentication uses cookies to store the session token by default. Which means your Angular application will receive the cookie when you first sign in. It will pass this for subsequent requests, and they will succeed while the session is still valid on the server.

The problem will be that Angular will lose the object state, when you refresh the page, that is telling it you have an active session. So you must restore this knowledge to Angular. There are two ways to tackle this:

  1. Check for the ss-id cookie when you application starts and assume you have a valid session. In other words, so restore to a signed in state, until you get a 401 error from the server. This is the quickest approach, and doesn't require additional overhead to check the session if somebody refreshes the page.

  2. Check for the ss-id cookie and make a test authenticated request to check the session is still valid.

If you need to restore other information such as the current logged in user's name etc, then you would need to store that in a cookie/local storage to restore it on refresh, or go with method 2, and retrieve it back from the server.

You can use $cookies provider to manage the session cookie.



来源:https://stackoverflow.com/questions/21975722/browser-refresh-lost-servicestack-authentication-session-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!