Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created October 24, 2018 21:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DavidWells/ea3e43886534ff7c3efb6d389766e588 to your computer and use it in GitHub Desktop.
Save DavidWells/ea3e43886534ff7c3efb6d389766e588 to your computer and use it in GitHub Desktop.
Clean your access token from URL to guard against user accidentally copy + pasting url elsewhere
function removeAccessTokenFromUrl() {
const { history, location } = window
const { search } = location
if (search && search.indexOf('access_token') !== -1 && history && history.replaceState) {
// remove access_token from url
const cleanSearch = search.replace(/(\&|\?)access_token([_A-Za-z0-9=\.%]+)/g, '').replace(/^&/, '?')
// replace search params with clean params
const cleanURL = location.toString().replace(search, cleanSearch)
// use browser history API to clean the params
history.replaceState({}, '', cleanURL)
}
}
// Site Url https://site.com?haha=false&lol=true&access_token=secret-stuffffffff
/* Run param cleanup after token grabbed by UI */
removeAccessTokenFromUrl()
// => https://site.com?haha=false&lol=true
/* user can no longer copy/paste token on accident or leak via airplay */
@nathfy
Copy link

nathfy commented Jul 4, 2022

This is an excellent gist - thanks @DavidWells - the regex didn't work so well for me, so slightly amended:

function removeAccessTokenFromUrl() {
  const { history, location } = window;
  const { search } = location;
  if (search && search.indexOf('access_token') !== -1 && history && history.replaceState) {
    const cleanSearch = search.replace(/(\&|\?)access_token[^\&]*/g, '').replace(/^&/, '?');
    const cleanURL = location.toString().replace(search, cleanSearch);
    history.replaceState({}, '', cleanURL);
  }
}
removeAccessTokenFromUrl();

@adriankiezik
Copy link

If other params like expires_in or refresh_token also annoy you, here is all in one:

const cleanSearch = search
    .replace(/(\&|\?)access_token[^\&]*/g, '')
    .replace(/(\&|\?)expires_in[^\&]*/g, '')
    .replace(/(\&|\?)provider_token[^\&]*/g, '')
    .replace(/(\&|\?)refresh_token[^\&]*/g, '')
    .replace(/(\&|\?)token_type[^\&]*/g, '')
    .replace(/(\&|\?)provider_refresh_token[^\&]*/g, '')
    .replace(/^&/, '?');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment