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
}
});
}
Related
My current api call flow from my client is as follows:
Send data to brand endpoint, retrieve recently inserted id, assign to userData.brand
Send data to user endpoint, retrieve recently inserted id, assign to userData.user
Send both values to userBrand endpoint
This seems like a costly process, so I am thinking of consolidating all the requests into one, but I am not sure how to process it from the server side. I know that I can just use one endpoint, but I don't know to how to use all the serializers/views against one endpoint.
So on the client side, this is what I have:
In brand.js
AdsomaService.registerUser(vm.userData).then(function(data) {
vm.successMessage = data.message;
vm.userBrandData.user = data.id;
}, function error(data) {
$log.info(data);
vm.errorMessage = data;
errorCount++;
});
AdsomaService.registerUserBrand(vm.userBrandData).then(function(data) {
vm.successMessage = data.message;
}, function error(data) {
$log.info(data);
vm.errorMessage = data;
errorCount++;
});
if(errorCount > 0) {
vm.message = vm.errorMessage;
angular.element('#errorMessage').appendTo('body').modal('show');
} else if(errorCount === 0) {
vm.message = vm.successMessage;
angular.element('#successMessage').appendTo('body').modal('show');
}
In adsoma.js
function registerUser(userData) {
var url = envService.read('apiUrl') + '/user_signup/';
var dataJSON = {
email: userData.email,
password: userData.password,
account_type: userData.accountType
};
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
function registerBrand(brandData) {
var url = envService.read('apiUrl') + '/brand_signup/';
var dataJSON = {
name: brandData.name,
brand: brandData.name,
email: brandData.email,
phone: brandData.phone,
website: brandData.website
};
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
function registerUserBrand(userData) {
var url = envService.read('apiUrl') + '/user_brand_signup/';
var dataJSON = {
user: userData.user,
brand: userData.brand
};
$log.info(dataJSON);
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
And on the server side, this is what I have:
In views.py
Code here: https://pastebin.com/P5ih75An.
In serialisers.py
Code here: https://pastebin.com/2zDgZDLc.
In a Word-addin I'm am trying to fetch data from AAD with the help of ADAL and microsoft.graph. Here is the code:
from app.js
var app = (function () {
"use strict";
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: '<TENANT>',
clientId: '<CLIENTID>',
redirectUri: '<THE-APP-ADDRESS>',
postLogoutRedirectUri: window.location.origin,
endpoints: {
officeGraph: 'https://graph.microsoft.com',
},
callback: userSignedIn,
popUp: true,
cacheLocation: 'localStorage'
};
function signIn() {
authContext.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
// showWelcomeMessage();
if (!err) {
console.log("token: " + token);
showWelcomeMessage();
}
else {
console.error("error: " + err);
}
}
function showWelcomeMessage() {
var authContext = new AuthenticationContext(config);
var $userDisplay = $(".app-user");
var $signInButton = $(".app-login");
var $signOutButton = $(".app-logout");
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
and main.js
function getDataFromSelection() {
var baseEndpoint = 'https://graph.microsoft.com';
var authContext = new AuthenticationContext(config);
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
authContext.acquireToken(baseEndpoint, function (error, token) {
if (error || !token) {
app.showNotification("Ingen token: ", "Du får logga in igen." + error); // + error
}
//var email = authContext._user.userName;
var url = "https://graph.microsoft.com/v1.0/" + config.tenant + "/me";
var html = "<ul>";
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: url,
dataType: "json",
headers: {
'Authorization': 'Bearer ' + token,
}
}).done(function (response) {
html += getPropertyHtml("Namn", response.displayName);
html += getPropertyHtml("Titel", response.jobTitle);
html += getPropertyHtml("Avdelning", response.officeLocation);
html += getPropertyHtml("Telefon jobb", response.businessPhones);
$("#results").html(html);
return postDataToContentControlers(response);
}).fail(function (response) {
// app.showNotification('Inloggningen slutade att fungera!', 'Du får logga ut och prova att logga in igen'); //response.responseText
}).always(function () {
console.log("AJAX is done!!")
})
});
} else {
app.showNotification('Error:', 'Något gick fel. Du får logga in igen.'); //result.error.message
}
}
);
}
On local wordklient it works but on Word online (Office 365 Pro Plus v.1609)
I get this when running the function getDataFromSelection();
Error from console
And right Before I login and i get confirmed and a token:
the parameter ConversationId is handled when you use microsoft-graph to GET mail-messages. Every mail has a conversationId... Why is it complaining about that regarding a GET against https://graph.microsoft.com/v1.0/me ?
Does anyone know how to get around this problem or Point me in the right direction? Thanks =)
EDIT: And I forgot to mention that this works online on Google Chrome but on Microsoft Edge The popup doesn't work at all regarding login Before even fetching any data. Only popup the addin again.
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;
}
}
I am using cryptojs to encrypt and decrypt a file. I also have a web service to upload the encrypted files to a server. I can upload and save the ecnrypted object as a file on the server, but when I decrypt it, the file does not open correctly. My concern is if I am saving the ecnrypted object correctly or not.
Tutorial that I followed initially: http://tutorialzine.com/2013/11/javascript-file-encrypter/
encryt method:
function encrypt() {
var folderPath = "C:\\User\\test\\javascript-file-encrypter\\";
selectedFiles = document.getElementById("MainContent_file1");
var sfile = selectedFiles.files[0];
var read = new FileReader();
read.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(read.result, '123456');
var ct2 = encrypted.toString();
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': ct2, 'fileName': sfile.name + '.encrypted' },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
}
read.readAsDataURL(sfile);
}
decrypt method:
function decrypt() {
var sfiles = document.getElementById("MainContent_file1");
var sfile = sfiles.files[0];
var freader = new FileReader();
freader.onload = function (e) {
var decrypted = CryptoJS.AES.decrypt(freader.result, '123456');
var dct = decrypted.toString(CryptoJS.enc.Latin1);
//var dct2 = decrypted.toString();
//console.log(dct);
//console.log(dct2);
debugger;
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': dct, 'fileName': sfile.name.replace('.encrypted', '') },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
};
freader.readAsText(sfile);
}
webservice method:
[WebMethod]
public bool FileUpload(string folderPath, string uploadData, string fileName)
{
bool returnValue = false;
try
{
File.WriteAllText(folderPath + fileName, uploadData);
returnValue = true;
}
catch (Exception ex)
{
returnValue = false;
}
return returnValue;
}
I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData)
{
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; //is not working
//var data = { username: loginData.userName, password: loginData.password, grant_type: "password" }; // I try this and is not working too
//data = $.param(data);
// how should I format my data for the web API to understand
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }
I made google search but still no solution; how can I resolve this issue?
thanks in advance!!