Passing sessionstorage item into a link JavaScript or HTML - javascript

I am trying to create a single sign in, and far as I can think this would probably be the best.
My backend receives the request, checks for email, creates a JWToken and adds it to a link sent per email to the user.
Something along this line
function loadWindow() {
var setsession = window.sessionStorage.setItem("JWT", 'tokentoken');
window.open('http://localhost:8080/html/reset-password.html')
}
there must be some way, but no matter how I do this, the page will not load with a sessionstorage set.

This seems to have actually fixed it!
It needed a const definition..
Just sticking it onto the end did not work, but this seems to:
function loadWindow() {
const myWindow = window.open('http://localhost:8080/html/reset-password.html');
myWindow.localStorage.setItem('JWT', 'cat');
}
Of course ideally would be directly sessionStorage, but that is not an option it seems.
I will probably have to write a script that removes it from local and rewrites it to sessionstorage. Not sure if all this is best practice security wise though..
EDIT:
come to think of it, this only works because I am running it from tab to tab, likely that when just opening a link from an email this won't work.
EDIT2:
I also appreached this differently,
By passing the token to the url.com/?token=randomtokennumbersletters
And then creating a js function loadFunction that runs upon loading the page
function loadFunction() {
if (sessionStorage.getItem('JWT') === null) {
let params = (new URL(document.location)).searchParams;
let token = params.get("token");
sessionStorage.setItem('JWT', token) // slaat de token van de link op in localstorage
}
}

Related

How to prevent tracking sensitive data in URLs?

Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.
Examples:
/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username#example.com
I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?
Since you are saying that it is your SPA, you might solve the problem by switching from GET requests (which have the parameters inside the URL) to POST requests. I do not know hotjar, but if you tell the tracking service to analyze URLs only, that would be an option worth considering.
Another option frequently used is to obfuscate your parameters in the URL, see e.g. Best way to obfuscate an e-mail address on a website? However, that is never a really safe solution for sensitive data, since the de-ciphering step is too easy, in particular if your man-in-the-middle has all requests ever send to your SPA.
Edit. I just found in the Hotjar allows RegEx. Assuming you could enter a regular expression of URL-parts to exclude.
The general syntax /foo/bar/ means that foo should be replaced by bar, in our case, we want to delete the given snippet, that why it is /foo//.
For the given case of the access token, the regular expression would be
/callback#access_token=[a-zA-Z0-9]{15}//
and respectively for the email part of the URL
/\?email=(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])//
This second RegEx partially taken from How to validate an email address using a regular expression?
It seems to me that it's reasonable to assume that tracking scripts will try to access window.location.href or similar to get the current url which they will store.
So a possible solution would be create a dynamic scope which has a different value for window.location.href (with all sensitive info filtered out)
This is how it might work:
// get the tracker script as a string, so you can eval it in a dynamic scope
let trackerScript = 'console.log("Tracked url:", window.location.href)';
// now lets lock it up
function trackerJail(){
let window = {
location: {
// put your filtered url here
href: "not so fast mr.bond"
}
}
eval(String(trackerScript))
}
trackerJail()
If the tracking snippet is wrapped in a function it might be possible to create a dynamic scope for it without running eval by overriding it's prototype instead. But I'm not sure you can count on tracker scripts being wrapped in a neat function you can modify.
Also, there are a couple more ways the script might try to access the URL, so make sure to cover all the exits
If you control the page and order of scripts, you could read the data from the url then delete it before anything else can get to it.
proofOfConcept.html
<script id="firstThingToLoad.js">
console.log(window.location.href);
const keyRegex = /key=[^&]*/;
const key = window.location.href.match(keyRegex);
console.log("I have key", key);
const href = window.location.href.replace(keyRegex, "");
history.replaceState({}, "", href);
</script>
<script id="someSnoopyCode.js">
console.log("I'm snooping: ", window.location.href);
</script>
<body>
Link to private
</body>
Of course the Link to private should not exist as is. Also, this does break refresh and most navigation in general, though there are ways to catch and save that.

my code storage data in local storage on a website but when i navigate through the pages and register a new user the old user are deleted

var userInfo = [];
var myCostum;
//documentgetElementById("registerForm");
document.getElementById("registerForm").addEventListener("click", function ()
{
//var register = document.querySelector('#registerForm');
var name = document.querySelector('#fN').value;
var lastN = document.querySelector('#lN').value;
var userName = document.querySelector('#uN').value;
var passwrd = document.querySelector('#pS').value;
userInfo.push([name,lastN,userName,passwrd]);
localStorage.setItem("myCostum", JSON.stringify(userInfo));
});
I am using separate files for j, my website has a navigation bar with home,register,login,about me and shopping car. this code works fine if i register more than one user, i can see the users in the local storage on all pages and i can even sign in. the problem is when i go to register again and register a new user the users that i reister before are deleted and replaced by the new user. also if i go to home page i can an error (Uncaught TypeError: Cannot read property 'addEventListener' of null
at even-listener.js:9). i just do not had idea why register page seems to work but the rest not. I had another code using onclick in html but the same it does not give any error in any page but the users gone when i register new one after navigating through my pages. this is the first time using localStorage and i do not can i do or if it is normal. i am stack and i need to keep adding more code but i want to solve this problem first.
Lots of things going on here, but let me start from the basics.
1st never use local storage for sensitive information such as usernames and passwords. There's a lot of sites that copy local storages and send it to malicious people.
2nd you could in theory use session storage limited to the tab, but you still could be under the danger of xss.
3rd when the browser closes, all your data will be lost from the local storage anyway
As for your code. Your user info, should not be initiated as empty. You must get the previous value from local storage and push to it. Otherwise you are just overriding the previous value.
var userInfo = JSON.parse(localStorage.getItem('myCustom'));

Detecting Unique Browser Tabs

On every page of my sites, I am using AJAX to poll the server and retrieve a list of messages. The server maintains a list of messages and the SessionId (I'm in an ASP.NET environment, but I feel like this question is applicable to any server side technology) that the message is intended for. If a message is found for the particular SessionId, it is returned to the client side script. I use a JavaScript library to create a notification (using noty, a Jquery Notification Plugin). Once it returns a particular message, the server discards that message.
This works well if the user only has a single tab/window open for a particular site. However, let's say they have two open and they do something that causes a warning message to be generated. I have no control over which tab the notification goes to, so the user may not end up seeing the warning message.
Is there a way of uniquely identifying a browser tab? Then I could pass this as one of the parameters in my AJAX call.
Firstly, polling doesn't seem good mechanism. It might hit your server down when you have large number of active users. Ideally you should return a message in the response to the request that was result of invalid action.
Still below solution might work for you. It is inspired by the reply of #SergioGarcia.
Keep a hidden input just before the end of your form tag, which stores a unique ID for identifying a tab uniquely. You will store the messages on server session against unique tabID,
<input type="hidden" id="hiddenInputTabId" value="<%=getValue()%>" />
and then define getValue.
function string getValue() {
var v = getValueFormBodyOrAccessValueDirectlyByMakingInput_a_ServerSideControl();
if (string.IsNullOrWhiteSpace(v)) {
return Guid.NewId();
} else {
return v;
}
}
Because it is a hidden input you should get it's value in the POSTed form body, and for ajax requests below snippet should take care of sending that value in header which you can access on server side.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("tabId", $('#hiddenInputTabId').val());
},
});
Same header can be check while returning the response to your polling requests and only respond message available against the provided tabId should be responded.
You can add a query string parameter called tabId and control it's binding to tab using javascript.
There is a functional prototype below:
$(function () {
// from: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
function getQueryStringParameter (sVar) {
return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
// from: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
window.tabId = getQueryStringParameter('tabId');
// tabId not defined, reload the page setting it
if (!window.tabId) {
window.tabId = newGuid();
}
// on click set the tabId of each link to current page
$(document).on('click', 'a', function (e) {
var $this = $(this);
var newLocation = $(this).attr("href");
// In page links
if (newLocation.match(/^#.+$/)) {
return;
}
// Outbound links
if (newLocation.match(new RegExp("^https?")) && !newLocation.match(new RegExp("^https?://" + window.location.host))) {
return;
}
// Insert tab id
if (newLocation.match(/(\?|&)tabId=[0-9a-f-]+/)) {
newLocation.replace(/(\?|&)tabId=[0-9a-f-]+/, (newLocation.indexOf('?') == -1 ? "?" : "&") + "tabId=" + window.tabId);
} else {
newLocation += (newLocation.indexOf('?') == -1 ? "?" : "&") + "tabId=" + window.tabId;
}
window.location.href = newLocation;
e.preventDefault();
});
});
If you enter a page in your application without setting the tabId parameter on query string, it will be set to a new UUID (Guid).
When the page has a tabId parameter on query string, it defines the window.tabId variable inside your page and you can use that in your application.
When the user click on any link in your page, a javascript event will be triggered and the link url will be redirected to match the current tabId. An right click to open in new tab or a middle click will not trigger that event and the user will be sent to a new tab without the query string parameters, so the new page will create a new tabId in that page.
You can see it working here: http://codepen.io/anon/pen/sCcvK
You can do it by generating a unique tab id with javascript by loading your client.
I strongly recommend you to use something for intertab communication, like intercom.js, which can broadcast the messages from a single tab with a single connection to every other tabs. Intertab works with socket.io, which has long polling fallback, so it may be good in your current system as well. I agree that polling is a poor choice, and you should use websockets instead.
If you use ZMQ on the server, then in the browser you can use NullMQ either (for websockets ofc). I think it does not have intertab support, so you should make your own intertab solution to make it work. It is not so hard to write such a system, you need only a common storage, for example localStorage, but it can be even cookie... If you don't have a storage event, you have to ping that storage for changes with setInterval. You have to store there the messages, and which tab broadcasts them (probably in a semaphore) and when was the last time it pinged the storage. After that you can keep each tab in sync with the others, or by using a unique tab id, you can send customized messages to any of the tabs. If the broadcast tab has a storage timeout (it did not ping the storage for a long while), then it is probably closed, so you should assign the broadcast service to another tab.
So what I ended up doing was changing how my notification framework functioned in order to prevent the need for identifying unique tabs. It's just too hard to layer information on the stateless web.
Instead of using Ajax to pump messages out to the client instantly, I build them up on each page into a List<Message> property. On PreRender I render them to the client with ClientScript.RegisterStartupScript(). But if I need to send the user to another page, I started using Server.Transfer() instead of Response.Redirect() instead so that it will preserve the message queue. The new page checks the old page to see if it exists and if is the correct Type. If it is the correct type, I cast it and retrieve the message queue from the old page and add them to the new page's queue. And since Server.Transfer() doesn't update the URL on the client, I also added a JavaScript function to manually push the state to the URL in supported browsers.
I know I took this in a little different direction than I did on the question, but I think I had been approaching it wrong in the beginning.

am using javascript to connect user login to my website

am using a JavaScript to connect users to the homepage after the processing page have finish loading and sent the user to the homepage of welcome.html but the fact is how do i end the session after the click the log out button, because after signing out and if they hit back they will still get back the welcome.html, i have try disabling the back button in the browser but that's not awesome, i just need to kill the session so that it won't get them back to the welcome.html after they sign out instead it goes back to login page and require them to sign back in to access the welcome.html, and in this fact am not using php or DB to connect the user login, am using javascript, i don't know if it could work maybe with php simple line of codes or tags.
Here is my JavaScript code, i use to connect the users:
function Login(FORM){
var done=0;
var username=document.login.username.value;
username=username.toLowerCase();
var password=document.login.password.value;
password=password.toLowerCase();
if (username=="jonson111" && password=="happy111") { window.location="HomeAccess_uche/processing.html"; done=1;}
if (username=="wilsonqaz" && password=="open123qaz") { window.location="HomeAccess_wilson/processing.html"; done=1; }
if (done==0) { alert("USERNAME OR PASSWORD IS NOT IN THE DATABASE PLEASE TRY AGAIN!"); }
}
am using dreamweaver and yes i know i will encrypt the Java codes so that users will not understand it, but i just need to end the session after they sign out, this have given me a hard time to figure out i have search everywhere in Google but nothing, anyone can help?
what ever you wrote is all about client side code. there is no point in worry about session , because you don't have a session at all. you are just using javascript. you don't have any server side code to handle session. anybody can see the user name and password by looking at your javascript code. More over once you redirect the page by window.location="HomeAccess_wilson/processing.html"; your " done=1; " and all the javascript variable will reset.
DISCLAIMER: This is a TERRIBLE IDEA. Your site will be completely unsecure. I am ONLY explaining a way to make it work so that a completely innocent, naive user would get the intended effect. Also, this will only work in modern browsers supporting local storage.
function save_login() {
localStorage.loggedIn = true;
}
function save_logout() {
localStorage.loggedIn = false;
}
Call those functions when they log in or log out, and then on every "secure" (but not really, this is totally unsecure) page you do
if (localStorage.loggedIn == false) {
window.location.href = "yoursite.com/login" //or whatever page you
//want to send them to
}

Show content based on user selection

Im building a site at the moment.
On the layout there are 3 flags for different countries.
Im wondering how i would go about displaying content based on what the user selects, and keeping that selection each time they come back to the site.
Obviously the first time they come to the site the default english will be shown, but once they click on a flag it would change.
Im taking im going to have to use javascript and cookies, i have been looking around and cant seem to find any examples, im wondering if someone could show me how to go about this.
Thanks
Cookies seems like the right idea:
http://www.google.co.uk/search?q=javascript+cookies
There are (probably) only two ways of doing this:
Cookies (i.e. mostly anonymous users)
Registration and getting users to login
For your needs, it sounds as though cookies would be enough.
http://www.quirksmode.org/js/cookies.html is absolutely worth reading from beginning to end.
I am giving a abstract idea of how i might do it..
In the html you write, put a javascript function which sets the flag's id in the browser cookie when you click the flag and then submit the request..
function setCookie(flag_id) //call this when the flag is clicked
{
var allcookies = document.cookie;
if(allcookies)
{
document.cookie += ';flagId=' + flag_id;
}
else
{
document.cookie='flagId=' + flag_id;
}
/*submit the form or whatever you would like to do when the flag is clicked*/
}
Thats it on the client part. You can specify the expiration time for the cookie as well.. for details you can refer the w3schools website. The cookie will stay in the browser and sent to the server on every request.
Now, on the server side, if you are using servlets, just use the following code to get the cookie in the doPost or doGet (in your case when the first request comes from the client).
.....
Cookies[] cookies = request.getCookies();
String flagId = null;
if(cookies != null)
{
for(String cookie:cookies)
{
if(cookie.getName().equals("flagId"))
{
flagId = cookie.getValue();
}
}
}
//use the flag id to decide your content here..
....
Hope this answers your question.

Categories

Resources