Why is my implementation of SSO using Ember-Simple-Auth with Auth0 getting stuck in a redirect loop? - authentication

I have an ember application that uses the Auth0 Ember Simple Auth addon to use the Ember-Simple-Auth functionality with Auth0's Lock.js. Recently I have been trying to implement single-sign-onfunctionality, such that if a user logs into a login portal application, their session will be preserved for other applications on the same domain, and they will not need to log in repeatedly. However my implementation of SSO is resulting in an infinite redirect loop between my login logic and Auth0's endpoint.
I have enabled SSO in the Auth0 application settings. My login is implemented in a few blocks.
My route.js contains a beforeModel() method which contains:
if (!get(session, 'isAuthenticated')){
// Forward to the login action
}
My login action:
login() {
var session = get(this, 'session');
session.authenticate('authenticator:myauthenticator', { authParams: { scope: 'openid' } });
}
This grabs the session object, and calls my custom authenticator. So far, this is basically just ember-simple-auth boilerplate, and complies with the examples supplied in the Auth0 Ember-Simple-Auth documentation.
Where I run into trouble is my custom authenticator. The base authenticator is here. You can see that it handles basic login logic easily, including showing the Auth0 lock when a user isn't authenticated. However it has no logic for handling the kind of SSO-session checking that I want to implement. So I implemented a custom authenticator as below, using examples provided by Auth0 for (basically) this exact scenario (you can see their examples [here], I'm using a slightly altered version)3:
authenticate(options) {
return new Ember.RSVP.Promise((res) => {
// the callback that will be executed upon authentication
var authCb = (err, profile, jwt, accessToken, state, refreshToken) => {
if (err) {
this.onAuthError(err);
} else {
var sessionData = { profile, jwt, accessToken, refreshToken };
this.afterAuth(sessionData).then(response => res(this._setupFutureEvents(response)));
}
};
var lock = this.get('lock');
// see if there's a SSO session available
lock.$auth0.getSSOData(function(err, data) {
if (!err && data.sso) {
// there is! redirect to Auth0 for SSO
options.authParams.callbackOnLocationHash = true;
lock.$auth0.signin(options.authParams, authCb);
} else {
// regular login
lock.show(options, authCb);
}
});
});
}
This behaves mostly as I would expect it to. When I log in with an existing session from another SSO-enabled app on the same domain, if (!err && data.sso) resolves to true, and lock.$auth0.signin(options.authParams, authCb) is called. However, this signin logic is not working as intended. Auth0.signin calls the Auth0.authorize method, which generates a target URL that looks something like:
https://mydomain.auth0.com/authorize?scope=openid&response_type=token&callbackOnLocationHash=true&sso=true&client_id=(MyClientIdHash)&redirect_uri=localhost%23access_token%3(MyAccessToken)%26id_token%3(MyIdToken1).(MyIdToken2).(MyIdToken3)token_type%3DBearer&auth0Client=(MyAuth0Client)
My application is then redirected to this URL for authorization. I get a 302 and am redirected back to the callback URL (my root page). Because there is a new page transition, if (!get(session, 'isAuthenticated')) is hit again. It returns false, and so the same logic repeats itself, looping indefinitely.
Does anyone have any insight on what I might be doing incorrectly here? The authorize endpoint seems to behave as if I were being authenticated, but then the authentication is never actually triggered. I've debugged through this code fairly extensively but seen no obvious red flags, and I've followed provided examples closely enough that I'm not sure what I would change. I'm not entirely sure where the failure to authenticate is happening such that get(session, 'isAuthenticated') is false.

Related

Why is ServiceStack JwtAuthProvider being invoked when service is specified to authenticate with GithubAuthProvider?

Exploring the ServiceStack authentication providers for the first time. Have gradually built up a test project by adding BasicAuthProvider and when that worked, added GithubAuthProvider. The last one added was JwtAuthProvider and that works as well. When I retested authentication with any of the previous authentication providers such as Github, for example, I find that the JwtAuthProvider lambda function for CreatePayloadFilter is still being invoked. This was not expected.
The AuthFeature plugin is as follows:
Plugins.Add(new AuthFeature(
() => new PartnerWebSession(),
new IAuthProvider[] {
new JwtAuthProvider(appSettings) { ... },
new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
new GithubAuthProvider(appSettings)
}));
I have created BasicHello, GithubHello and JwtHello service models with different end points for use with each of the authentication providers with routes:
/basic/{Name}
/github/{Name}
/jwt/{Name}
The AuthenticateAttribute has been attached to the Service classes designed to work with these models and they each specify the Provider to use, e.g.:
[Authenticate(Provider = "basic")]
public class BasicAuthentication : Service
{
public object Any(BasicHello request)
{
return new BasicHelloResponse { Result = $"{nameof(BasicAuthentication)} says Hello, {request.Name}!" };
}
}
Testing using Visual Studio debug and Chrome browser. Have ensured that no previous cookies JWT are hanging around from previous tests by clearing cookies for all time. I enter the URL:
http://localhost:52070/api/github?name=stephen
This takes me to the ServiceStack rendered authentication screen with login dialogue and "Sign In with Github" button. Click the "Sign In with Github" button which takes me to the "Sign in to GitHub" page provided by GitHub. Successfully authenticate, and then code execution hits a breakpoint I've set in CreatePayloadFilter lambda of the JwtAuthProvider.
I did not expect this. Is this an error or am I doing something wrong?
If you have the JWT AuthProvider registered it populates the successful Auth Response with a populated JWT Token that encapsulates the partial authenticated session.
The stateless client JWT Token (i.e. instead of server session cookies) can then be used to make authenticated requests after a successful OAuth Sign In.

How do you solve Auth0's URL Mismatch error

I'm trying to implement Auth0 with lock (version 10.11.0) inside my Angular2 app. Auth0 works if I list every possible route in Auth0's client's Allowed Callback URLs setting. It seems Auth0 picks up the callback URL from whatever URL the user happens to be on when they decide to login. This is not a scalable approach. How do you solve this?
I've tried entering a redirectUrl value in auth options. This gets me a little further in that the app does redirect to the URL supplied, however, Auth0 lock's authenticated callback never fires so I cannot retrieve authenticated user's profile.
So, I'm stuck. It seems my only course of action is to list every conceivable route in Auth0's client's Allowed Callback URLs setting and pray the guys from marketing do not come up with more routes.
Here's my code:
let options =
{
auth:
{
//redirectUrl: 'http://localhost:4200',
//redirect: true,
responseType: 'token',
params:
{
scope: 'openid user_id name nickname email picture'
}
}
};
this.lock = new Auth0Lock('xxx', 'yyy', options);
this.lock.on("authenticated", (authResult) =>
{
console.log('#### AUTH RESULTS:', authResult);
localStorage.setItem('id_token', authResult.idToken);
this.lock.getProfile(authResult.idToken, (error, profile) =>
{
if (error)
{
return;
}
console.log('#### AUTHENTICATED USER PROFILE:', profile);
});
}
Any ideas on how to make Auth0 work so you do not have to list every possible route a user can be on before deciding to authenticate?

Aurelia Security - Authentication & Authorization

These are a couple general questions to really see different implementations of detecting authentication and authorization using Aurelia. All of this is speaking within the context of a secured back-end service.
Say you are using cookie authentication with the server. How are you acknowledging that cookie in Aurelia to display to the user that they are logged in?
In the Aurelia documentation(seen here), we can see the following:
class AuthorizeStep {
run(navigationInstruction, next) {
if (navigationInstruction.getAllInstructions().some(i =>
i.config.settings.roles.indexOf('admin') !== -1)) {
var isAdmin = /* insert magic here */false;
if (!isAdmin) {
return next.cancel(new Redirect('welcome'));
}
}
return next();
}
}
What does /* insert magic here */ look like for you? What should it look like?
The app I am currently working on requests a token from the server at the 'login' route using XHR. If this request is successful, and a token was received from the backend, then the token is stored in a cookie and we route away from the login page to the main content of the app. We could then set a global variable 'loggedIn' to display that the user is logged in, etc. Each time we make further requests to the backend via XHR, we send the token with the request.
The 'magic' in the authorize step is just some logic that checks to see if the user is logged in, or in the example above, an admin.

unauthorizedRedirect set to false, still redirecting

I'm writing some REST api for my cake 3.0 application, and I need to set $this->Auth->unauthorizedRedirect to false, as the manual says that this would prevent my application to redirect to login url for unauthorized requests.
http://api.cakephp.org/3.0/class-Cake.Auth.BasicAuthenticate.html
The problem is that I'm trying to set it in my Users controller, and it doesn't work:
class UsersController extends AppController {
public function initialize() {
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow(['logout']);
// Change the authentication mode when using REST api
if(! $this->RequestHandler->accepts('html')) {
$this->Auth->unauthorizedRedirect = false;
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
}
}
}
This scripts works fine as detecting if a user is actually registered, but fails when I try to use wrong authentication data, showing the login form instead of throwing an error. What am I doing wrong?
Authentication and authorization are two different things
You are mixing up authentication and authorization, that's two different things. Logging in a user is authentication, testing whether a logged in user is allowed to access a specific action is authorization.
So the unauthorized redirect configuration applies to logged in users when accessing actions.
Handling unauthenticated requests
What you are looking for, ie throw an exception on unauthenticated requests, is done by the basic authentication adapter by default, so I assume that you actually aren't using this adapter!?
So if you are using a different adapter, this behavior is best implemented in either your controller where you are trying to identify the user
$user = $this->Auth->identify();
if (!$user) {
throw new ForbiddenException('Stop! Hammer time!');
} else {
$this->Auth->setUser($user);
}
or, in case you want the exception to be thrown for every controller, in a custom authentication adapters unauthorized() method, which is being invoked on unauthenticated requests before executing possible redirects. Quote from the docs:
Cookbook > Authentication > Handling Unauthenticated Requests
When an unauthenticated user tries to access a protected page first the unauthenticated() method of the last authenticator in the chain is called. The authenticate object can handle sending response or redirection by returning a response object, to indicate no further action is necessary. Due to this, the order in which you specify the authentication provider in authenticate config matters.
If authenticator returns null, AuthComponent redirects user to login action. [...]
Here's a simple example that extends the form authentication handler:
src/Auth/MyCustomAuthenticate.php
namespace App\Auth;
use Cake\Auth\FormAuthenticate;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Request;
use Cake\Network\Response;
class MyCustomAuthenticate extends FormAuthenticate
{
public function unauthenticated(Request $request, Response $response)
{
if(!$request->accepts('text/html')) {
throw new ForbiddenException('Ah ah ah! You didn\'t say the magic word!');
}
}
}
Controller
$this->loadComponent('Auth', [
'authenticate' => [
'MyCustom'
]
]);
See also
Cookbook > Authentication > Creating Custom Authentication Objects
Cookbook > Authentication > Using Custom Authentication Objects

ember simple auth session, ember data, and passing a Authorization header

I have a working oauth2 authentication process where I get an access token (eg from facebook) using ember simple auth, send it to the back end which calls fb.me() and then uses JWT to create a token. This token is then sent back to the ember app, which then has to send it with every server request, include those requests made by ember-data.
I also need to have this token available after a browser reload.
I have tried many options, where I set a property 'authToken' on the session - I believe that this uses local storage to persist the authenticated session.
But I always seem to have trouble with coordinating the retrieval of this token - either I don't have access to the session, or the token is no longer on the session, or I can't change the ember data headers.
Does anyone have a working simple example of how this can be done - I think it should be easy, but I'm obviously missing something!
Thanks.
Update
The only thing I've been able to get working is to use torii as shown below, but the session content is still lost on refresh - I can see its still authenticated, but its lost the token I set here. So I'm still looking for a real solution.
authenticateWithGooglePlus: function () {
var self = this;
this.get('session').authenticate('simple-auth-authenticator:torii', 'google-oauth2')
.then(function () {
resolveCodeToToken(self.get('session'), self);
});
}
resolveCodeToToken gets the bearer token from the server, sets it on the session and then transitions to the protected page:
function resolveCodeToToken(session, route) {
var authCode = session.content.authorizationCode;
var type = session.content.provider.split('-')[0];
$.ajax({
url: 'http://localhost:4200/api/1/user/auth/' + type,
data: {authCode: authCode}
}).done(function (response) {
// todo handle invalid cases - where user is denied access eg user is disabled
session.set('authToken', response.token);
route.transitionTo('activity', moment().format('DDMMYYYY'));
});
}
And I have a custom authorizer for putting the token (stored in the session) on every request:
import Base from 'simple-auth/authorizers/base';
export default Base.extend({
authorize: function(jqXHR, requestOptions) {
var accessToken = this.get('session.content.authToken');
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
jqXHR.setRequestHeader('Authorization', accessToken);
}
}
});
I'm not sure why this.get('session.content.authToken') would be undefined after a refresh, I thought by default the session was persisted in local storage. The fact that it is authenticated is persisted, but thats useless without the token since the server will reject calls to protected endpoints.
You'd want to implement your own custom authenticator that first gets a token from Facebook and then sends that to your own server to exchange it for a token for your app. Once you have that you get authorization of ember-data requests as well as session persistence etc. for free.
Have a look at this example: https://github.com/simplabs/ember-simple-auth/blob/master/examples/7-multiple-external-providers.html