Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle fetching new tokens (aka refresh of tokens) using authorize prompt none in an iframe #226

Merged
merged 4 commits into from
Nov 1, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,8 @@ auth0.getDelegationToken(options, function (err, delegationResult) {

### Refresh token

> This methods will be deprecated soon. Use `silentAuthentication` instead

If you want to refresh your existing (not expired) token, you can just do the following:

```js
Expand All @@ -606,6 +608,61 @@ auth0.refreshToken(refresh_token, function (err, delegationResult) {
});
```

### Silent Authentication

If you want to fetch a new token because your existing token is expired (or soon to expire), you can fetch a new one doing the following:

```js
auth0.silentAuthentication({}, function(err, result){
// Get here the new result.id_token
})
```

This by default will use the callback url defined in the constructor. If this callback url is the same that handle the regular authentication callback, you will need to have in mind that you will need to handle the case where the user is already loged in and reached that path again.

If you want to use a different one, you can send the new `callbackURL` in the options param:

```js
auth0.silentAuthentication({
callbackURL: "https://.../silentCallback"
}, function(err, result){
// Get here the new result.id_token
})
```

There are two ways this method works. The default behaviour will try to parse the callback url hash, but it also support `postMessage` to send the authentication result from the callback page back to the sdk.

```js
auth0.silentAuthentication({
usePostMessage:true,
callbackURL: "https://.../silentCallback"
}, function(err, result){
// Get here the new result.id_token
})
```

An example of the callback page is the following:

```html
<!DOCTYPE html>
<html>
<head>
<script src="/auth0.js"></script>
<script type="text/javascript">
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: '...'
});
var result = auth0.parseHash(window.location.hash);
if (result) {
parent.postMessage(result, "https://.../"); //The second parameter should be your domain
}
</script>
</head>
<body></body>
</html>
```

### Validate User

You can validate a user of a specific connection with his username and password:
Expand Down
17 changes: 17 additions & 0 deletions example/callback.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<script src="/auth0.js"></script>
<script type="text/javascript">
var auth0 = new Auth0({
domain: 'mdocs.auth0.com',
clientID: '0HP71GSd6PuoRYJ3DXKdiXCUUdGmBbup'
});
var result = auth0.parseHash(window.location.hash);
if (result) {
parent.postMessage(result, "http://localhost:9999/"); //The second parameter should be your domain
}
</script>
</head>
<body></body>
</html>
2 changes: 1 addition & 1 deletion example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -237,4 +237,4 @@ <h2>Passwordless authentication with SMS</h2>
</div>
</div>
</body>
</html>
</html>
65 changes: 53 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var json_parse = require('./lib/json-parse');
var LoginError = require('./lib/LoginError');
var use_jsonp = require('./lib/use_jsonp');

var SilentAuthenticationHandler = require('./lib/SilentAuthenticationHandler');

/**
* Check if running in IE.
*
Expand Down Expand Up @@ -705,6 +707,21 @@ Auth0.prototype._buildAuthorizationParameters = function(args, blacklist) {
return query;
};

Auth0.prototype._buildAuthorizeUrl = function(options) {
var qs = [
this._getMode(options),
options,
{
client_id: this._clientID,
redirect_uri: this._getCallbackURL(options)
}
];

var query = this._buildAuthorizeQueryString(qs);

return joinUrl('https:', this._domain, '/authorize?' + query);
}

/**
* Login user
*
Expand Down Expand Up @@ -741,18 +758,7 @@ Auth0.prototype.login = Auth0.prototype.signin = function (options, callback) {
};

Auth0.prototype._authorize = function(options) {
var qs = [
this._getMode(options),
options,
{
client_id: this._clientID,
redirect_uri: this._getCallbackURL(options)
}
];

var query = this._buildAuthorizeQueryString(qs);

var url = joinUrl('https:', this._domain, '/authorize?' + query);
var url = this._buildAuthorizeUrl(options);

if (options.popup) {
this._buildPopupWindow(options, url);
Expand Down Expand Up @@ -1638,6 +1644,41 @@ Auth0.prototype.getDelegationToken = function (options, callback) {
});
};

/**
* Fetches a new id_token/access_token from Auth0
*
* @example
*
* auth0.silentAuthentication({}, function(error, result) {
* if (error) {
* console.log(error);
* }
* // result.id_token
* });
*
* @example
*
* auth0.silentAuthentication({callbackUrl: "https://site.com/silentCallback"}, function(error, result) {
* if (error) {
* console.log(error);
* }
* // result.id_token
* });
*
* @method silentAutnetication
* @param {Object} options
* @param {function} callback
*/
Auth0.prototype.silentAuthentication = function (options, callback) {
var usePostMessage = options.usePostMessage || false;

delete options.usePostMessage;

options = xtend(options, {prompt:'none'});
var handler = new SilentAuthenticationHandler(this, this._buildAuthorizeUrl(options));
handler.login(callback, usePostMessage);
};

/**
* Trigger logout redirect with
* params from `query` object
Expand Down
100 changes: 100 additions & 0 deletions lib/IframeHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
var IframeHandler = function (options) {
this.auth0 = options.auth0;
this.url = options.url;
this.callback = options.callback;
this.timeout = options.timeout || 60 * 1000;
this.timeoutCallback = options.timeoutCallback || null;
this.usePostMessage = options.usePostMessage || false;
this.iframe = null;
this.timeoutHandle = null;
this._destroyTimeout = null;
this.transientMessageEventListener = null;
this.transientEventListener = null;
}

IframeHandler.prototype.init = function (url) {
this.iframe = document.createElement('iframe');
this.iframe.style.display = "none";
this.iframe.src = this.url;

var _this = this;

if (this.usePostMessage) {

// Workaround to avoid using bind that does not work in IE8
this.transientMessageEventListener = function(e) {
_this.messageEventListener(e);
};

window.addEventListener("message", this.transientMessageEventListener, false);
}
else {

// Workaround to avoid using bind that does not work in IE8
this.transientEventListener = function() {
_this.loadEventListener();
};

this.iframe.addEventListener("load", this.transientEventListener, false);
}

document.body.appendChild(this.iframe);

this.timeoutHandle = setTimeout(function() {
_this.timeoutHandler();
}, this.timeout);
}

IframeHandler.prototype.messageEventListener = function (e) {
this.callbackHandler(e.data);

this.destroy()
}

IframeHandler.prototype.loadEventListener = function () {
var result = this.auth0.parseHash(this.iframe.contentWindow.location.hash);

if (!result) return;

this.callbackHandler(result);

this.destroy();
}

IframeHandler.prototype.callbackHandler = function (result) {
var error = null;

if (result.error) {
error = result;
result = null;
}

this.callback(error, result);
}

IframeHandler.prototype.timeoutHandler = function () {
if (this.timeoutCallback) {
this.timeoutCallback();
}
this.destroy();
}
IframeHandler.prototype.destroy = function () {
var _this = this;

if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle);
}

this._destroyTimeout = setTimeout(function () {
if (_this.usePostMessage) {
window.removeEventListener("message", _this.transientMessageEventListener, false);
}
else {
_this.iframe.removeEventListener("load", _this.transientEventListener, false);
}
document.body.removeChild(_this.iframe)
}, 0);
}


module.exports = IframeHandler;
34 changes: 34 additions & 0 deletions lib/SilentAuthenticationHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
var IframeHandler = require('./IframeHandler');

var SilentAuthenticationHandler = function (auth0, authenticationUrl, timeout) {

this.auth0 = auth0;
this.authenticationUrl = authenticationUrl;
this.timeout = timeout || 60 * 1000;
this.handler = null;

}

SilentAuthenticationHandler.prototype.timeoutCallback = function () {

console.error('Timeout during silent authentication.')

}

SilentAuthenticationHandler.prototype.login = function (callback, usePostMessage) {

this.handler = new IframeHandler({
auth0:this.auth0,
url: this.authenticationUrl,
callback: callback,
timeout: this.timeout,
timeoutCallback: this.timeoutCallback,
usePostMessage: usePostMessage || false
});

this.handler.init();

}


module.exports = SilentAuthenticationHandler;
Loading