ZenDesk App OAuth browser-based authentication - javascript

I'm working on a ZenDesk app that pulls customer info from a back-end system. We need to authenticate against that system using OAuth 2's browser-based authentication flow.
It's no problem to include a link to the authentication page, something like:
https://oauth2server.com/auth?
response_type=token&
client_id=CLIENT_ID&
redirect_uri=REDIRECT_URI&
scope=photos
Once the user has logged in, though, the OAuth server wants to redirect the client and include the authorization token. So the REDIRECT_URI would typically look like:
https://example.zendesk.com/agent/#token=ACCESS_TOKEN
However, ZenDesk already makes use of the fragment identifier to indicate what content to show on the page:
https://example.zendesk.com/agent/#/dashboard
https://example.zendesk.com/agent/#/tickets/1234
My ZD App only appears on certain pages, so how can I both
have my app rendered and Javascript run, and
have the fragment identifier with the auth token available?
(I do have control over the backend OAuth server, so if you can't think of a nice clean way to accomplish this, OAuth server-side hack suggestions are also gratefully accepted.)

Here's a really simple ZenDesk App (framework version 0.5) that
authenticates against Google (in a seperate popup window)
fetches a custom ticket field value from the currently visible ticket
retrieves the Google user's name
In manifest.json, this ZenDesk App should specify "location": "ticket_sidebar".
app.js
(function (window) {
return {
zenDeskSubdomain: 'YOUR_ZENDESK_SUBDOMAIN',
googleClientId: 'YOUR_GOOGLE_CLIENT_ID',
events: {
'app.activated': 'onActivate',
'app.deactivated': 'onDeactivate',
'click .loginout': 'onLogInOutClick',
'click .show-username': 'onShowUserNameClick'
},
requests: {
getUserInfo: function (access_token) {
return {
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + access_token,
type: 'GET',
proxy_v2: true
};
}
},
onActivate: function () {
console.info("onActivate()");
this.accessToken();
var user_id = this.ticket().customField("custom_field_22931898");
this.$('.userid').text(user_id);
},
onDeactivate: function () {
console.info("onDeactivate()");
if (this.timer) {
clearTimeout(this.timer);
}
},
onShowUserNameClick: function () {
var access_token = this.accessToken();
if (!access_token) {
console.info("Can't do it! No access_token!");
return;
}
this.ajax('getUserInfo', access_token)
.done(function (data) {
console.info(data);
this.$('.username').text(data.name);
});
},
onLogInOutClick: function (event) {
if (this.accessToken()) {
this.logout(event);
} else {
this.login(event);
}
},
login: function (event) {
console.info("login()");
event.preventDefault();
var popup = this.createLoginPopup();
this.awaitAccessToken(popup);
},
logout: function (event) {
console.info("logout()");
event.preventDefault();
this.accessToken(null);
console.info(" access_token = " + this.accessToken());
this.$('.loginout').text('login');
},
createLoginPopup: function () {
console.info("createLoginPopup()");
return window.open(
'https://accounts.google.com/o/oauth2/auth?response_type=token&client_id=' + this.googleClientId + '&redirect_uri=https%3A%2F%2F' + this.zenDeskSubdomain + '.zendesk.com%2Fagent%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile',
'Login Popup',
'width=400,height=400');
},
timer: null,
awaitAccessToken: function (popup) {
console.info("awaitAccessToken()");
if (this.isLoaded(popup)) {
console.info(" popup is loaded");
} else {
console.info(" popup is NOT loaded; sleeping");
var t = this;
this.timer = setTimeout(
function () { t.awaitAccessToken(popup); },
1000);
return;
}
var access_token = this.parseAccessToken(popup.location.href);
if (access_token) {
console.info(' access_token = ' + access_token);
popup.close();
this.accessToken(access_token);
} else {
services.notify('Error requesting code...');
}
},
isLoaded: function (win) {
try {
return ('about:blank' !== win.location.href)
&& (null !== win.document.body.innerHTML);
} catch (err) {
return false;
}
},
parseAccessToken: function (uri) {
var match = uri.match(/[#&]access_token=([^&]*)/i);
return match[1] || null;
},
accessToken: function (value) {
if (1 === arguments.length) {
console.info("Storing access_token = " + value);
this.store({ access_token: value });
}
var token = this.store('access_token');
console.info("access_token = " + value);
var loginout = this.$('.loginout');
if (token) {
loginout.text('logout');
} else {
loginout.text('login');
}
return token;
}
};
}(this));
layout.hdbs
<header>
<span class="logo"/>
<h3>{{setting "name"}}</h3>
</header>
<section data-main/>
<footer>
<div><a class="loginout">login</a></div>
<div><a class="show-username">show username</a></div>
<div><b>user id: </b><span class="userid">unknown</span></div>
<div><b>username: </b><span class="username">unknown</span></div>
</footer>
Google OAuth configuration
Configure Google OAuth to allow traffic from your application.
Redirect URIs
http://localhost:XXX - for the ZAT development/testing environment
https://YOUR_ZENDESK_SUBDOMAIN.zendesk.com/agent/ - for production
Javascript Origins
http://localhost:XXX - for the ZAT development/testing environment
https://YOUR_ZENDESK_SUBDOMAIN.zendesk.com - for production

You can use a lightweight server-side app to manage the authorization flow and tokens. The Zendesk app can communicate with it through the framework's iframe helper. I wrote an extended tutorial for the Zendesk Help Center at https://support.zendesk.com/hc/en-us/articles/205225558.

Related

Trying to implement ADAL (Azure AD) in Javascript, keep getting a login/redirect loop

So I've got to create a calendar in html that gets events from Outlook and then deploy that as a custom page to Sharepoint, so it can be included as a webpart/iframe in site collections.
The problem is that I've tried adding ADAL security because you need to be logged in & send a token to Microsoft Exchange Online API in order to get calendar events etc. To display the calendar part, I'm using FullCalendar.io .
Now I've been keep getting a login/redirect loop that never ends. Does anyone see the fault in code? Here it is:
var $this = this;
$(document).ready(function() {
debugger;
window.config = {
tenantId: {tenant},
clientId: {clientid},
popUp: true,
callback: callbackFunction,
redirectUri: {custom aspx page URL on our Sharepoint},
cacheLocation: 'localStorage'
};
var authenticationContext = new AuthenticationContext(config);
authenticationContext.handleWindowCallback();
function callbackFunction(errorDesc, token, error, tokenType) {
alert('callbackFunction reached!');
}
var items = null;
if (authenticationContext.TokenCache) {
items = authenticationContext.TokenCache.ReadItems();
}
if (authenticationContext['_user']) {
authenticationContext.acquireToken(config.clientId, function (errorDesc, token, error) {
if (error) { //acquire token failure
if (config.popUp) {
// If using popup flows
authenticationContext.acquireTokenPopup(config.clientId, null, null, function (errorDesc, token, error)
{});
}
else {
// In this case the callback passed in the Authentication request constructor will be called.
authenticationContext.acquireTokenRedirect(config.clientId, null, null);
}
}
else {
//acquired token successfully
// alert('token success');
$this.DisplayEvents(token);
}
});
}
else {
// Initiate login
authenticationContext.login();
}
});
function DisplayEvents(adalToken) {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function(start, end, timezone, callback) {
var headers = new Headers();
var bearerToken = "Bearer " + adalToken;
headers.append('Authorization', bearer);
var options = {
method: 'GET',
headers: headers
};
var exchangeEndpoint = 'https://outlook.office.com/api/v2.0/me/events';
fetch(exchangeEndpoint, options).then(function (response) {
alert('Response data from successful call: ' + response);
});
}
});
}
So the code does get to "acquire token" and then the last "else", so "$this.DisplayEvents(token)" does get called! However, after acquire token, the app just keeps redirecting forever and ever... The Reply URL in my Azure AD App registration is also the window.config redirectURL value, or else I'd get an error stating the reply URL's don't match between request and Azure.
Does anyone know where it's going wrong?
I can reproduce your issue on my side by using your code. If you use authContext.getCachedUser() to check login status, redirect issue will disappear.
if (authContext.getCachedUser()) {
authContext.acquireToken(config.clientId, function (error, token) {
if (error) { //acquire token failure
if (config.popUp) {
// If using popup flows
authContext.acquireTokenPopup(config.clientId, null, null, function (errorDesc, token, error) { });
}
else {
// In this case the callback passed in the Authentication request constructor will be called.
authContext.acquireTokenRedirect(config.clientId, null, null);
}
}
else {
//acquired token successfully
// alert('token success');
alert(token);
}
});
}
else {
// Initiate login
authContext.login();
}

ADAL.js Token renewal operation failed due to timeout Azure AD Auth Web API

We have experienced the following problem:
We had implemented Azure AD authenticated web API and we have been successfully had been making calls to it with ADAL 1.0.12 (we had our own wrapper around it for processing iframe for silent login).
Now we got rid all together of our wrapper and upgraded to the latest version and started to get the problem described here: token renewal operation timed out.
The Azure AD architecture behind the API is very simple: a registered web app with Read directory data and Sign in and read user profile permissions. We have another native app registered with permissions to the web app (Access to the Web APP NAME HERE). Both applications have oauth2AllowImplicitFlow set to true in their manifests.
Both apps have registered a wildcard redirect URIs for https://ourtenant.sharepoint.com/* (we are making the calls from SharePoint to the web API). In addition, the native client app has registered redirect URI to the unique URI (App ID URI) of the web API app.
Both apps have been granted admin consent before - they were working fine with the old version of ADAL.js
So, here is some code. Please, note that we had tried both without displayCall callback (with page refresh directly on the current page) and with page refresh (check the commented code in initLogin method). Also we had a switch for generating a popup or an iframe with a callback on successful login.
The problem is with authContext.acquireToken. Note that if we call OurNamespace.authContext.getCachedToken(OurNamespace.clientId) we get a stored token for the resource.
Note that also, we are calling properly handleWindowCallback after each page refresh / iframe / popup.
Happens regardless of the browser.
OurNamespace = {
serviceMainUrl: "https://localhost:44339",
webApiAppIdUri: "WEB-API-URI",
tenant: "TENANT",
clientId: "NATIVE-APP-GUID", // Native APP
adalEndPoints: {
get: null
},
adal: null,
authContext: null,
dummyAuthPage: null,
usePopup: true,
init: function () {
this.dummyAuthPage = "DummmyLogin.aspx";
OurNamespace.adalEndPoints.get = OurNamespace.serviceMainUrl + "/api/values";
OurNamespace.authContext = new AuthenticationContext({
tenant: OurNamespace.tenant + '.onmicrosoft.com',
clientId: OurNamespace.clientId,
webApiAppIdUri: OurNamespace.webApiAppIdUri,
endpoints: OurNamespace.adalEndPoints,
popUp: false,
postLogoutRedirectUri: window.location.origin,
cacheLocation: "localStorage",
displayCall: OurNamespace.displayCall,
redirectUri: _spPageContextInfo.siteAbsoluteUrl + "/Pages/" + OurNamespace.dummyAuthPage
});
var user = OurNamespace.authContext.getCachedUser(); // OurNamespace.authContext.getCachedToken(OurNamespace.clientId)
if (user) {
OurNamespace.azureAdAcquireToken();
} else {
OurNamespace.initLogin();
}
},
initLogin: function () {
//OurNamespace.authContext.config.displayCall = null;
//var isCallback = OurNamespace.authContext.isCallback(window.location.hash);
//OurNamespace.authContext.handleWindowCallback();
//if (isCallback && !OurNamespace.authContext.getLoginError()) {
// window.location.href = OurNamespace.authContext._getItem(OurNamespace.authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
//}
OurNamespace.authContext.login();
},
displayCall: function (url) {
var iframeId = "azure-ad-tenant-login",
popup = null;
if (OurNamespace.usePopup) {
popup = window.open(url, 'auth-popup', 'width=800,height=500');
} else {
var iframe = document.getElementById(iframeId);
if (!iframe) {
iframe = document.createElement("iframe");
iframe.setAttribute('id', iframeId);
document.body.appendChild(iframe);
}
iframe.style.visibility = 'hidden';
iframe.style.position = 'absolute';
iframe.src = url;
popup = iframe.contentDocument;
}
var intervalId = window.setInterval(function () {
try {
// refresh the contnetDocument for iframe
if (!OurNamespace.usePopup)
popup = iframe.contentDocument;
var isCallback = OurNamespace.authContext.isCallback(popup.location.hash);
OurNamespace.authContext.handleWindowCallback(popup.location.hash);
if (isCallback && !OurNamespace.authContext.getLoginError()) {
popup.location.href = OurNamespace.authContext._getItem(OurNamespace.authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
window.clearInterval(intervalId);
if (OurNamespace.usePopup) {
popup.close();
}
var user = OurNamespace.authContext.getCachedUser();
if (user) {
console.log(user);
} else {
console.error(OurNamespace.authContext.getLoginError());
}
}
} catch (e) { }
}, 400);
},
azureAdAcquireToken: function () {
OurNamespace.authContext.acquireToken(OurNamespace.adalEndPoints.get, function (error, token) {
if (error || !token) {
SP.UI.Status.addStatus("ERROR", ('acquireToken error occured: ' + error), true);
return;
} else {
OurNamespace.processWebApiRequest(token);
}
});
},
processWebApiRequest: function (token) {
// Alternatively, in MVC you can retrieve the logged in user in the web api with HttpContext.Current.User.Identity.Name
$.ajax({
type: "GET",
url: OurNamespace.adalEndPoints.get,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {},
headers: {
'Authorization': 'Bearer ' + token
},
success: function (results) {
var dataObject = JSON.parse(results);
SP.UI.Status.addStatus("Info", "ADAL GET data success: " + dataObject.webApiUser);
$(".grid-info").html("<h1 class=\"h1\">Current Web API authenticated user: " + dataObject.webApiUser + "</h1>");
},
error: function (xhr, errorThrown, textStatus) {
console.error(xhr);
SP.UI.Status.addStatus("ERROR", ('Service error occured: ' + textStatus), true);
}
});
}
}
I am testing using the 1.0.15 adal.js and get the access token successfully by using the authContext.acquireToken which actually call the this._renewToken(resource, callback) to acquire the access token by the hide iframe. Here is the full test sample code for your reference:
<html>
<head>
<script src="/js/1.0.15/adal.js"></script>
<script>
var config = {
tenant: 'adfei.onmicrosoft.com',
clientId: '7e3b0f81-cf5c-4346-b3df-82638848104f',
redirectUri: 'http://localhost/spa.html',
navigateToLoginRequestUrl:false,
};
var authContext=new AuthenticationContext(config);
var hash = window.location.hash;
if(hash.length!=0){
authContext.handleWindowCallback(hash);
var user=authContext.getCachedUser();
}
function login(){
authContext.login();
}
function acqureToken(){
authContext.acquireToken("https://graph.microsoft.com", function(error, token, message){
console.log(token)
})
}
</script>
</head>
<body>
<button onclick="login()">Login</button>
<button onclick="acqureToken()">AcquireToken</button>
</body>
</html>
Is it helpful? Or would you mind sharing a run-able code sample for this issue?
I'm not sure if what version of adal.js you are using. But there is a loadFrameTimeout setting for the config object that you can set in milliseconds. Check the top of your adal.js file and it should be there.

Getting messages in chat history to display in messenger Pubnub

I have come to post this question after 2 days of torture not being able to understand how I can actually publish the historic messages stored on my pubnub storage account. To try and understand it at its most basic I have made a chat app and used the history function as described in the SDK but still every time I refresh the page the messages are lost. I have tried the backfill and the restore attributes in subscribe with no luck. All I want to do is click refresh on chrome and see the messages still there.
<div><input id=input placeholder=you-chat-here /></div>
Chat Output
<div id=box></div>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.0.min.js"></script>
<script>(function(){
var pubnub = new PubNub({ publishKey : 'demo', subscribeKey : 'demo' });
function $(id) { return document.getElementById(id); }
var box = $('box'), input = $('input'), channel = 'chat';
pubnub.addListener({
message: function(obj) {
box.innerHTML = (''+obj.message).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML
}});
pubnub.history({
channel: 'chat',
reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
count: 100, // how many items to fetch
callback : function(msgs) {
pubnub.each( msgs[0], chat );
}
},
function (status, response) {
// handle status, response
console.log("messages successfully retreived")
});
pubnub.subscribe({channels:[channel],
restore: true,
backfill: true,
ssl: true});
input.addEventListener('keyup', function(e) {
if ((e.keyCode || e.charCode) === 13) {
pubnub.publish({channel : channel, message : input.value,x : (input.value='')});
}
});
})();
</script>
</body>
EDIT: updated link that was broken. New version of history function is called fetchMessages.
I think your history code is not correct. No need for the callback as your code response will be in the function argument. This example is from the JavaScript SDK docs.
// deprecated function
pubnub.history(
{
channel: 'chat',
},
function (status, response) {
var msgs = response.messages;
if (msgs != undefined && msgs.length > 0) {
// if msgs were retrieved, do something useful
console.log(msgs);
}
}
);
// latest function (response output format has changed)
pubnub.fetchMessages(
{
channels: ['chat']
},
(status, response) => {
console.log(msgs);
}
);

Retrieving data from an inappbrowser

I am currently building an Ionic hybrid application.
Unfortunately, I am having difficulties accessing the response data of the request during the Facebook sign-up process.
We want to retrieve data from an inappbrowser and are using Cordova's inappbrowser for a callback. Unfortunately we can't. What is the best way of accomplishing this?
function InAppBrowser($scope, $cordovaInAppBrowser, $rootScope, $http, $window) {
var durr;
$scope.facebook = facebook;
$scope.foobar = foobar;
function facebook() {
var options = {
location: 'no',
clearcache: 'yes',
toolbar: 'no'
};
durr = $cordovaInAppBrowser.open('https://www.facebook.com/dialog/oauth?scope=email,public_profile,user_friends,user_likes,user_photos,user_posts&client_id={client_id}&redirect_uri={callback_url}', '_blank', options)
.then(function(e) {
console.log(e);
})
.catch(function(e) {
console.log(e);
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event) {
$cordovaInAppBrowser.executeScript(
{ code: "localStorage.setItem('hurr', document.body.innerHTML)" },
function(data) {
console.log(data);
});
});
}
function foobar() {
console.log(durr);
// console.log(durr.localStorage.getItem('hurr'));
}
}
I don't use this for Facebook but the plugin Oauth. This plugin uses InAppBrowser : " https://github.com/nraboy/ng-cordova-oauth/blob/master/README.md ". It's very simple to use.
$cordovaOauth.facebook("Your client id", "scope", "options").then(function (result) {
Console.log(JSON.stringify(result);
// Get the information about the user's account
// See more at https://developers.facebook.com/docs/graph-api/reference/v2.2/user
$http.get("https://graph.facebook.com/v2.2/me", {
params: {
access_token: "your token",
fields: "id,last_name,first_name,gender,picture,birthday,location,email",
format: "json"
}
}).then(function (result) {
/** your code **/
}

Angular refresh kills user session

I have a problem with my angular app- after a user signs in, if he hits the refresh button, the signin info is lost and the app redirects to the log in page. I found a SO answer for something similar here using $cookieStore but I don't think it can work for me as I'm not using cookies. Can anyone suggest a solution? Here's my authorization service-
var app = angular.module('myApp.services');
app.factory('SignIn', ['$resource', '$q', function($resource, $q) {
var signInUrl = 'https://example.com'
var API = $resource(signInUrl, {}, {
signIn: {
withCredentials: true,
url: signInUrl + '/session',
method: 'POST'
},
signOut: {
url: authApiUrl + '/session',
method: 'DELETE'
},
currentUser: {
url: signInUrl + '/users/#me',
method: 'GET'
}
});
var _currentUser = undefined;
return {
isAuthenticated: function() {
return !!_currentUser;
},
getUser: function(){
var d = $q.defer();
// If _currentUser is undefined then we should get current user
if (_currentUser === undefined) {
API.currentUser(function(userData) {
_currentUser = userData;
d.resolve(userData);
}, function(response) {
if (response.statusCode === 401) {
_currentUser = null;
d.resolve(_currentUser);
} else {
d.reject(response);
}
});
} else {
d.resolve(_currentUser);
}
return d.promise;
},
signIn: function(username, password){
var d = $q.defer();
API.signIn({email: username, password: password}, function(data, headers){
_currentUser = data;
d.resolve(_currentUser);
}, d.reject);
return d.promise;
},
signOut: function(){
var d = $q.defer();
API.signOut(function(){
_currentUser = null;
d.resolve();
}, d.reject);
return d.promise;
}
};
}]);
If you just need to keep track of the _currentUser data past a refresh then you could use sessionStorage within the browser. That extends all the way back to IE 8 and we really shouldn't be supporting any browsers before that anyway.
Usually these things are done with cookies though. When the client first makes a connection to the server (even before the first API call in some cases) a cookie is sent to the client so the server can maintain a session associated with that particular client. That's because the cookie is automatically sent back to the server with each request and the server can check its local session and say, "Oh, I'm talking to this user. Now I can use that additional piece of context to know if I can satisfy their API call or not."
You don't show any of your other API calls here but I'm guessing that you're sending something out of the _currentUser with each API call to identify the user instead? If so, that certainly works, and it avoids the need to synchronize cookies across multiple servers if you're clustering servers, but you're going to have to use something local like sessionStorage or localStorage that won't get dumped like your current in-memory copy of the data does when you refresh the page.

Categories