Password stored in google chrome's browser memory - javascript

When I login and logout from my application, my username and password are stored into chrome browser memory. When I create a dump file from the task manager for that particular process Id and open that file in WinHex tool and search for username or password field I'm able to see my password in clear text and now I want to encrypt or clear that password field.
function onLogin(btnName) {
var parameters = getFormValues();
//if (!validateParameter(parameters.userName, parameters.password))
// return;
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader(parameters.antiForgeryTokenName, parameters.antiForgeryToken);
}
});
var getSecuritySettingsUrl = getVirtualDirectoryUpdatedURL("/login/GetSecuritySettings");
$.ajax({
url: getSecuritySettingsUrl,
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function (result) {
try {
var response;
if (result.IsHashed) {
var decryptedData = decryptWithDefaultSetting(result.viewData);
if (decryptedData.isError) {
alert(decryptedData.result);
return;
}
response = JSON.parse(decryptedData.result);
}
else {
response = JSON.parse(result.viewData);
}
if (response.IsPasswordHashed) {
if (isNullOrUndefined(response.SaltText)) {
throw new Error("Please refresh the page and try again");
}
encriptPass = encryptByInputKey(parameters.form["Password"].value, response.SaltText).result;
}
$('#btnType').val(btnName);
$('form input[name="Password"]').val(encriptPass);
$('#loginForm').submit();
} catch (error) {
console.log(error);
if (!isNullOrUndefined(error)) {
if (!isNullOrUndefined(error.message)) {
alert(error.message);
}
else if (!isNullOrUndefined(error.Message)) {
alert(error.Message);
}
else {
alert("Some error has occurred. Please refresh the page and try again");
}
}
}
},
error: function (xhr, textStatus, error) {
console.log(xhr);
alert("Please refresh the page and try again : " + xhr.statusText);
}
});
}

I have solved this problem earlier by salting and hashing the user entered password in the UI and passing both the salted value and hash to server for authentication. The same salt has to be applied during the server side password validation.

Related

Submitting a From to a REST API using JQuery does not work

I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading

How to handle laravel TokenMismatchException when session expires

When the session is expired, User cant log back in without a page refresh because the _token in ajax headers is expired(AKA TokenMismatchException). I cant handle the exception by redirecting user to a log in page because the login is an overlay modal and the request is handled via ajax.
I thought i could catch the mismatch exception in Handler.php and return a json response with a session token. and on the client side, use the new token to continue the intended process. However, when i use the new token passed from server, the session token will be changed again on server side which results another TokenMismatchException.
So how should i handle the exception in a secured way without refreshing a page?
Here's what i have right now:
setup csrf_token in a global js file:
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
});
});
render method in app/exceptions/handler.php:
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if ($e instanceof TokenMismatchException)
{
if ($request->ajax()) {
return response()->json([
'message' => 'TokenMismatchException',
'token' => csrf_token()
]);
}
}
else
{
return parent::render($request, $e);
}
}
in authentication.js:
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked')
},
success: function(response) {
if (response.message === 'TokenMismatchException') {
console.log(response); //message and token exist
//if catch the exception, use the new token to set up the ajax headers and login again
$.ajaxSettings.headers["X-CSRF-TOKEN"] = response.token;
console.log($.ajaxSettings.headers["X-CSRF-TOKEN"]);
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked'),
},
success: function(res) {
console.log(res);
},
error: function(err) {
console.log(err);
}
});
}
console.log('logged in');
},
error: function(xhr, status, err) {
}
});
thanks in advance.
In your render function, you've to check for a specific TokenMismatchException. So may be you can try something like this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json('msg', 'Your session has expired. Please try again.');
}
You may also pass a new csrf_token along with the json so that you can replace the old one with the new one and send the form request again.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json(['msg'=> 'Your session has expired. Please try again.', 'token'=> csrf_token()]);
}
I haven't tested this code. But this should get you started.
Also, if you want, you can use a package: https://github.com/GeneaLabs/laravel-caffeine

javascript: Requires upload file”,“type”:“OAuthException Facebook user already registered

I am using the Facebook JavaScript SDK to upload photos to facebook timeline.
Initially I used this code and it worked:
<script language="javascript">
function test() {
var message = document.getElementById('txtMessage').value;
FB.login(function (response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
FB.api('https://graph.facebook.com/me/photos', 'post', {
message: message,
status: 'success',
access_token: access_token,
url: 'http://dotnetspeaks.com/xyz.jpg'
}, function (response) {
if (!response || response.error) {
alert('Error occured:' + response);
} else {
alert('Successfully posted on wall.');
}
});
} else {
alert('Interrupted.');
}
}, { scope: 'user_photos,photo_upload,publish_stream,offline_access' });
}
</script>
I have added FB.init above all.
This code worked once but then gave me the error that "user is already signed in".
Then I found FB.getLoginStatus() function to check if the user is logged in or not. I changed to code to below
<script language="javascript">
function test() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.api('https://graph.facebook.com/me/photos/uploaded', 'post', {
message: "hii",
status: 'success',
access_token: accessToken,
url: "images/brave_t.jpg"
}, function (response) {
if (!response || response.error) {
alert('Error occured:' + response);
} else {
alert('Successfully posted on wall.');
}
},{scope: 'publish_actions,photo_upload'});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
}
</script>
I added the scope field to check if that works as "{scope: 'publish_actions,photo_upload'}" but that too didn't work. I am repeatedly geeting this error : "message: "(#324) Requires upload file" .
Please help me to resolve this.
I want to upload image to the Facebook timeline
Thanks in advance
The URL has to be absolute, you are trying to use a relative path:
url: "images/brave_t.jpg"
In the first code part, you are doing it in a correct way:
url: 'http://dotnetspeaks.com/xyz.jpg'
Btw, there is no photo_upload permission, publish_actions is all you need. If you need more information about FB.login and FB.getLoginStatus, take a look at this article: http://www.devils-heaven.com/facebook-javascript-sdk-login/

Destroy a "User" from parse sdk with javascript

i need to delete a user form parse sdk with javascript, i tried loading the user query and then calling the destroy() but it gives me:
[HTTP/1.1 400 Bad Request]
my code is here
var query = new Parse.Query("User");
query.equalTo("email", 'wathmal#hotmail.com');
query.find().then(function(results) {
console.log(results[0]);
results[0].destroy();
});
this won't destroy the user. can anybody help?
with the help of Bjorn's answer i figured out a way doing it. i had to use REST api of parse sdk and generate a DELETE request with a proper session key of the user.
var CurrentUser = Parse.User.current();
console.log(CurrentUser);
var sessiontoken;
Parse.User.logIn(CurrentUser.attributes.username, document.getElementById("curpassword").value, {
success: function (user) {
user.set("StayLoggedIn", "false");
console.log(user._sessionToken);
sessiontoken = user._sessionToken;
user.save();
$.ajax({
url: 'https://api.parse.com/1/users/' + user.id,
type: 'DELETE',
headers: {'X-Parse-Application-Id': APP_ID, 'X-Parse-REST-API-Key': REST_KEY, 'X-Parse-Session-Token': sessiontoken},
success: function (result) {
// Do something with the result
alert("you have successfully deleted your account.");
Parse.User.logOut();
window.location.href = "index.html";
}
});
// location.reload();
},
error: function (user, error) {
//alert(error);
alert("incorrect username or password");
}
});

can't get return value in nodejs?

I have following tutorial how to request value from node js and return back to user requested but not successful.
here my javascript code..
put('id','coment',function(data) {
var obja = JSON.parse(data);
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1); //its no result value
});
})
function put(id, data, callback) { //call from here to nodejs
$.ajax('http://localhost:8000/' + id + '/', {
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(false); }
});
}
and here my nodejs
connection.query("SELECT field1,field2,field3 from table", function(e, row) {
if(e)
{
console.log('An error occured: '+e)
}
else
{
try{
res.write(JSON.stringify(row)); //send value back to user requested
res.end();
}catch(ex){
console.log('errror' + ex) ;
}
}
});
in console, the query was load normally but when I try send back to user requested, it gets no value.
My problem is, why can't I send back to user requested?
You shouldn't need var obja = JSON.parse(data); because it will already be parsed by jQuery due dataType: 'json' being set.
Also based on the code you've shown obja is an Array so instead of this:
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1);
});
Just do this:
obja.forEach(function(row){
alert(row.field1);
});

Categories