Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Amazon Cognito user credentials without local storage

I'm using Amazon Cognito for user login for a website with the Javascript SDK which uses local storage to save the user's credentials which are used for things like auto login. This doesn't work when running from a local file on your computer.

Is it possible to direct the Javascript SDK to save user credentials through some other means instead of local storage when running a website locally?

I've seen references to changing the storage object but I can't find any samples on how to actually implement a custom storage solution. https://github.com/aws/amazon-cognito-identity-js/pull/363

like image 437
Berry Blue Avatar asked Feb 05 '18 21:02

Berry Blue


1 Answers

To answer your exact question

As shown in the pull request you linked to you can now specify a Storage object for the pool to use. There are two built in Storage objects according to MDN: localStorage and sessionStorage. You may be able to use sessionStorage as is (I haven't tried it). It will survive page reloads but is cleared when the page/tab is closed. New tabs get a new sessionStorage object.

let pool = new CognitoUserPool({ 
  UserPoolId, 
  ClientId, 
  storage: window.sessionStorage 
});

If that doesn't work you'll need to build an object that implements the Storage API. It's pretty simple and would not take much to do. There are 5 total methods and most can be mapped 1:1 with a simple Object

Storage.key(int n); // Return the Nth key
Storage.getItem(string key) // return the value for given key
Storage.setItem(string key, string value) // store a value at key
Storage.removeItem(string key) // remove the value for key
Storage.clear() // delete all values

Here is an NPM package that implements the Storage API in memory. Downside is that page refreshes would clear it.

As you can see from the source code it's not very complicated.

However

In my opinion a better alternative would be to use a very simple server like serve or a Web Server for Chrome to serve the files over http so that localStorage (and many other parts of the page) work as you would expect.

like image 173
tsdorsey Avatar answered Oct 21 '22 01:10

tsdorsey