After a user enters credentials on the login page, a post request is sent to the web server, which sends a cookie (if successful). On the client side, simultaneously, write the user details to my global redux store. On successful authentication from the server, I call window.location.href = 'newURL'. This call reloads my app. Now the user info I stored to the global store is lost, and I am not able to display username which was enetred by the user. How can I access the user credentials?
Thanks in advance :)
As mentioned in comments.
You need to use either localStorage or sessionStorage to keep the data alive.
For eg
localStorage.setItem("user", {"name": "abc"});
Now, though you logged out your data will be there in localStorage and you get the data using
localStorage.getItem("user");
If you want to remove then
localStorage.removeItem("user") or window.localStorage.removeItem('user');
Same applies to sessionStorage as well
Related
I'm using Node(axios,pinia)+Vue3 as frontEnd,and node(express,bcrypt,jsonwebtoken)+MongoDB as BackEnd to build a SPA web.
I use JWT for login authentication and save at localstorage.
Now it only can keep login.
Hoping have Selectable "Keep Login" function like some forum usually have.
(After closing browser/shotdown will need to login again.)
I don't use sessionStorage for this website user often open new tab.Some cross tab problem bother me and I thought cookie might got better solution.
I can imagine only "Always login"/"temp login" can be done likes. But with selectable I can't thought a simple way to apply it.
Like now I'm thought still use LocalStorage(LS) for Vue to run,but also have Session Cookie(as Cookie)(Not sure the name but the cookiewill be deleted when all webs closed).
Keep login need no change for me.If set to temp login, then the setting will be save to JWT,all front/back could know.
Use cache as signal for closing browser,if (temp login)&&(no cookie){clear LS}.
However I wonder the localStorage can be extract so the func will not safty enough? Then a school computer will be disaster
I'm new to cookie/session,and want to know any better way for safty/efficent. I will prevent XSS.
It would be wonderful to have your experienct/Idea!
Poor language and consult at here first,If any describe not clear/too detail please tell me,I will try to edit it, thanks!
The use of JWT is below:
BackEnd use bcrypt verify user password and response a JWT(with userID for db to find,also save to user login record DB) and other basic user info.
Some response data like JWT,basic userinfo will be save in localstorage to let Vue decide display login/admin/different page.
When user send a request(some login-action), JWT will also be send as BearToken to bo verified by backEnd that JWT was record in that user login record.
So JWT is the only security key,the user's login record should have same JWT.
Because it save in localstorage,user must logout!(Despite I can set some limit time.)
I would like to know - how to implement a login in HTML5 where I want Login to be shown if session doesn't exists on first load and if any session with user data exists i want 'name' to be displayed instead of 'login'.
You cannot manage sessions without a server side language like PHP, Ruby, etc. HTML5 and JavaScript can only manage things on the user's side.
You should look at HTML5 Local Storage
https://www.w3schools.com/html/html5_webstorage.asp first. If this is not what you want then you have to use a server side language.
For using session object for login, you can do something like(PHP example):
1.Store the user's details in session object when user logs in via xyz.com/login
$_SESSION["username"] = "username";
2.When the user visits xyz.com next time, check if a value of a session object already exists.
if(isset($_SESSION["username"])){
// redirect to user profile etc.
}
else{
// show login page - xyz.com/login
}
For more info: https://www.w3schools.com/php/php_sessions.asp
I set up a sessionless app that uses OAuth2 password grant authentication. When a user logs into my app with a username and password I save the access token in sessionStorage which is valid for 30 minutes. I also save a refresh token in sessionStorage in case I need to extend the session longer than 30 minutes. The refresh token is valid for 30 days.
If the 'remember me' checkbox is selected on login I save the access and refresh tokens in localStorage so they will persist as long as the refresh token is valid.
Both of these seem to work fine except for a couple of issues:
If the browser is left open and the user doesn't log out the session could potentially last for 30 days.
sessionsStorage doesn't persist between windows/tabs so if the user opens a new window they need to log in again. This is not an issue when the 'remember me' checkbox is selected since localStorage does persist between windows.
I think using refresh tokens is not safe for JavaScript applications - you need to access the /token endpoint and authenticate using the application's secret. But the secret gets public in such applications.
I would prefer the OAuth2 implicit flow and getting new token from the /auth endpoint with prompt=none parameter (from OpenID Connect). But with the implicit flow, you would either need to get a longer living ID token (and ask for an access token with the ID token later) or to implement the "remember me" at the OAuth2 (better option - can be used by any application). That would also solve the problem #2 with passing tokens between tabs.
By the "session" you mean using the refresh token to generate access tokens for 30 days? If that's a problem, you can implement some activity detector which would log the user out if there is no activity for e.g. 30 minutes.
It's possible to use the localStorage as a kind of message passing service, so you can keep the tokens in the sessionStorage, but a new tab can use the localStorage to request the token from existing tabs. For more info see http://www.codediesel.com/javascript/sharing-messages-and-data-across-windows-using-localstorage/
Code example from the linked article:
function eventListener(e) {
if (e.key == 'storage-event') {
output.innerHTML = e.newValue;
}
}
function triggerEvent() {
localStorage.setItem('storage-event', this.value);
}
window.addEventListener("storage", eventListener, true);
data.addEventListener("keyup", triggerEvent, true);
The workflow would be like this:
New tab is opened and writes an arbitrary value to the localStorage with a key indicating that it needs a token. The key can be "newTabOpened". The new tab starts listening to changes of another key "oauth2token".
The existing tab listens to the changes of the "newTabOpened" key and as a reaction, it writes its token value under the "oauth2token" key.
The new tab reads the token and removes it from the localStorage.
i am creating an application.i want to redirect from my application to another site.I am using username as session variable.But when it call back to my application then i dont getting session variable.I got the session variable as null.
I am using window.location.assign("sitename")
I have an application with my own username and password...after i login redirect to another site that site providing a login page.we enter the username and password of that site..then there is some processing is going on .then i got the result.but when return back i got the session null session.setAttribute("username", username);
session.setAttribute("password", password);
I got the answer
We can use local storage concept.So that we can store the username and password in the browse itself when we redirect to another site.In the browser inspect -> Resources - >Local storage. In local storage we hava ea url and it should be the same in the browser.
//to set the username
localStorage.setItem("username", "Smith");
//to Retrieve the usernamelocalStorage.getItem("lastname");
Thank you
Here is my problem :
I'm creating a web app with loopback (great framework :) ) with an AngularJS client, everything works well but impossible to reload the page without being disconnected. This behaviour is normal, however I would like to persist the session with a "Remember me" checkbox and just avoid to be disconnect on page reload. The access token is stored in localStorage, I think I have to create a cookie on myself but the main point, how do I avoid disconnection ? And redirection to forbidden page. Then should I do this on server-side or client-side both ? I'm lost actually...
I did start from this application on github if you wish to have a better idea of the project:
https://github.com/strongloop/loopback-getting-started-intermediate
You shouldn't need to create a separate cookie to store the authToken if it's already in localStorage. The part you will need to modify is inside app.js, the .run() block, which checks for the existence of $rootScope.currentUser to determine if you're logged in, which will not be persisted across browser reloads.
The code creates $rootScope.currentUser in Auth.js. The .run() block of app.js simply checks for the existence of $rootScope.currentUser to determine if you are logged in.
So you'll need to change how you detect logged out state from simply checking for $rootScope.currentUser to attempting an actual call to User.getCurrent() or something. If you are logged in, the call will include the auth token in the headers, if not, you'll get a 401 status code response and you can redirect to the login page in that case.