Created
October 24, 2018 21:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 */ |
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
This is an excellent gist - thanks @DavidWells - the regex didn't work so well for me, so slightly amended: