M
M
merss2016-10-08 22:44:24
JavaScript
merss, 2016-10-08 22:44:24

How to get a token from the address bar (oauth)?

The address bar receives a token like:

http://hostname/#access_token=kcReHCFnOhJZWcqEJxmgbBdNMt4SXPLK&state=

and it is constantly updated, what condition to prescribe so that it stops updating
tried like this:
if(location.hash.length > 1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-10-09
@merss

You must save the received access token ( access token ). In the case of JavaScript , this can be done in sessionStorage (within the current session) or localStorage (save for a long time), or transferred to the server (more reliable option).
The code for storing the access token in the browser's storage might be something like this:

if (window.location.hash != '') {
  var hash = window.location.hash.substring(1);
  var accessToken = hash.substr(hash.indexOf('access_token=')).split('&')[0].split('=')[1];
  sessionStorage.setItem('access_token', accessToken);
  // для безопасности, из url лучше удалить access_token
  window.location.hash = '';
  // window.location.href = window.location.href.substr(0, window.location.href.indexOf('#'))
}

// и далее использовать сохраненный маркер доступа
var currentAccessToken = sessionStorage.getItem('key');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question