Implement clientside token-based authentication using plain Javascript/AJAX - javascript

Can anyone point me to an article that explains clientside token auth implementation using Javascript?
I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.
Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?

I have personally used JSON web tokens in one of my projects.
http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.
Once you get the token as a response to the client side, you can store the token on window.localStorage.
var credentials = {
username : document.getElementById("username").value,
password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
url: url + '/register',
type: 'POST',
data: { username: credentials.username, password: credentials.password },
success: function(Data) {
window.localStorage.setItem('token', Data.token);
},
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
error: function() {
alert('Error occured');
}
});
});
Then you can attach it in an AJAX call as a header while navigating to other pages.
$.ajax
({
type: "GET",
url: "index1.php",
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization',window.localStorage.getItem('token'));
},
success: function (){
alert('Thanks for your comment!');
}
});

This worked for me..
var token = gettoken();
function getDatatypes() {
if (isEmpty(token)) {
token = gettoken();
}
var request = getDatatypesFromApi();
request.success(function (data) {
alert('success!');
});
request.error(function (httpObj, textStatus) {
if (httpObj.status == 401)
gettoken();
});
}
function getDatatypesFromApi() {
var request = $.ajax
({
type: "GET",
url: "http://yoururl.com/",
data: '',
headers:{
'Authorization': 'Basic ' + token
},
dataType: "json",
timeout: 5000,
});
return request;
}
function gettoken() {
var credentials = {
username: "userid",
password: "PASS",
domain: "",
extensionsAppId:"{extAppId}"
};
var url = "http://thelinktoresource/"
$.ajax({
url: url,
type: 'GET',
data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (Data) {
console.log(Data);
token = Data.replace(/"/ig, '');
return token;
},
error: function () {
alert('Error occured');
return "undefined";
}
});
}
function isEmpty(strIn) {
if (strIn === undefined) {
return true;
}
else if (strIn == null) {
return true;
}
else if (strIn == "") {
return true;
}
else {
return false;
}
}

Related

GMAIL API sending reply with file attachment

I'm currently working on gmail API base on this thread
https://stackoverflow.com/a/31792244/6766279
everything works fine if I just need to compose a new email, but I don't know how to do it if i need to reply. i tried changing the data with threadId, and receives an error, 'Recipient address required.'
/* Send the mail! */
$.ajax({
type: "POST",
url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart",
contentType: "message/rfc822",
beforeSend: function (xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + ACCESS_TOKEN);
},
data: {
raw: mail,
threadId: thread.id
},
success: function (res) {
resolve(res)
},
error: function (error) {
console.log('ERROR:', error.responseJSON.error.message);
window.open(`${location.origin}/api/google/rest/verify`, "", "width=500, height=500");
}
});
I really need help.
/* Send the reply! */
$.ajax({
type: "POST",
url: "https://www.googleapis.com/gmail/v1/users/me/messages/send",
headers: {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + ACCESS_TOKEN,
},
data: JSON.stringify({
raw: btoa(mail).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''),
threadId : threadId
}),
success: function(res){
console.log(res)
},
error: function(error){
console.log('ERROR:', error);
}
});
Solved with this,

Identity.IsAuthenticated return false in an ASP.Net Web API

After a successful login, the returned value is always false. I'm using the default Authentication system that's provided by Microsoft.Identity ("Individual User Accounts" option) with no modifications. Any thoughts?
[HttpGet]
[Route("get-userId")]
public bool CurrentUserId()
{
return User.Identity.IsAuthenticated;
}
Client-side codes:
Login.html:
$(document).ready(function () {
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
window.location.href = "Momo.html";
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
Momo.html:
$(document).ready(function () {
if (sessionStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
success: function (response) {
console.log(response);
}
});
console.log(response) returns false.
You need to send the token to the server with each request. Add the following to your Ajax call:
headers: { "Authorization": 'Bearer ' + token }
You can rewrite your code like this:
$(document).ready(function () {
var token = sessionStorage.getItem('accessToken');
if (token == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
headers: { "Authorization": 'Bearer ' + token },
success: function (response) {
console.log(response);
}
});

How can I prevent getting a dialog popup window to login with basic authentication?

Currently we are trying to access the reed.co.uk api and get the json results of jobs from an account. I have managed to access the API in chrome and get the results but in Safari (Version 10.0.1 (12602.2.14.0.7)) and Firefox(v 50.1.0) I get the dialog pop up that asks me to log in.
I have tried multiple versions of Ajax to get this working but nothing seems to fix the issue at all. Here is what I have got:
var clientId = "c*****-***-****-****-*********0";
var clientSecret = "";
var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
$.ajax({
type: 'GET',
url: 'http://www.reed.co.uk/api/1.0/search?employerId=488552',
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
crossDomain: true,
headers: {
'Authorization': 'Basic ' + authorizationBasic
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
},
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false,
success: function (result) {
var token = result;
console.log(token);
},
//complete: function (jqXHR, textStatus) {
//},
error: function (req, status, error) {
alert(error);
}
});
Request headers Chrome:
Request headers firefox
This is the information reed.co.uk returns to you when accessing the results from their API:
You will need to include your api key for all requests in a basic
authentication http header as the username, leaving the password
empty.
Can anyone see why this would happen?

Translating a rest API call from angular to jQuery

Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}

Clear Phonegap's InAppBrowser Cache

I am using Google authorization into my app. It works perfectly,
but the problem is cache not clear when someone logout from app.
I have tried adding clearcache=yes and clearsessioncache=yes, but they do not seem to do anything. Without clearing the cache when someone tries to log back in it validates the token with the previously signed in account.
Is there a way I can delete everything associated to the InAppBrowser ?
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
var authWindow = window.open(authUrl,'_blank','location=no,toolbar=no,clearsessioncache=yes');
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function (response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
googleapi.authorize({
client_id: 'client_id',
client_secret: 'client_secret-key',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
getDataProfile();
});
}
function getDataProfile() {
var term = null;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {
},
success: function (data) {
var item;
var OAuthToken = accessToken;
var OAuthAccessToken = data.id;
var username = data.email;
var firstname = data.given_name;
var lastname = data.family_name;
var ExternalIdentifier = data.id;
var Email = data.email;
var ProviderSystemName = "ExternalAuth.Google";
ExternalResponseInsert(apiSecretKey, storeId, languageId, username, firstname, lastname, Email, ExternalIdentifier, OAuthToken, OAuthAccessToken, ProviderSystemName);
}
});
//disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
}
});
}

Categories

Resources