Giter VIP home page Giter VIP logo

ember-simple-auth's Introduction

Ember Simple Auth API docs

CI

Discord

  • Ember Simple Auth supports all Ember.js versions starting with 3.28.
  • Doesn't support IE11
  • Node >=16 is required
  • Supports Embroider see our ember-try scenario and test app for guidance.

Note

Ember Simple Auth was written and is maintained by Mainmatter and contributors. We offer consulting, training, and team augmentation for Ember.js – check out our website to learn more!

Ember Simple Auth

Logo

Ember Simple Auth is a lightweight library for implementing authentication/ authorization with Ember.js applications. It has minimal requirements with respect to application structure, routes etc. With its pluggable strategies it can support all kinds of authentication and authorization mechanisms.

Table of Contents

Basic Information

Usage

Core Feature Guides

Other Guides

Other Resources

What does it do?

  • it maintains a client side session and synchronizes its state across multiple tabs/windows of the application
  • it authenticates the session against the application's own server, external providers like Facebook etc.
  • it is easily customizable and extensible

How does it work?

Ember Simple Auth consists of 3 main building blocks - the session, a session store and authenticators.

The session service is the main interface to the library. It provides methods for authenticating and invalidating the session as well as for setting and reading session data.

The session store persists the session state so that it survives a page reload. It also synchronizes the session state across multiple tabs or windows of the application so that e.g. a logout in one tab or window also results in a logout in all other tabs or windows of the application.

Authenticators authenticate the session. An application can leverage multiple authenticators to support multiple ways of authentication such as sending credentials to the application's own backend server, Facebook, github etc.

Example App

Ember Simple Auth comes with a test app that implements a complete auth solution including authentication against the application's own server as well as Facebook, authorization of Ember Data requests and error handling. Check out that test app for reference. To start it, run

git clone https://github.com/mainmatter/ember-simple-auth.git
cd ember-simple-auth/packages/test-app
pnpm install && ember serve

and go to http://localhost:4200.

Installation

Installing the library is as easy as:

ember install ember-simple-auth

Upgrading from a pre-3.0 release?

The 3.0 release of ember-simple-auth removes previously deprecated code, introducing some breaking changes, but thankfully there is an v3 upgrade guide.

Upgrading to 4.0 release?

The 4.1 release introduced a session#setup that fixes build issues for typescript and embroider users, due to ESA using initializers. Consult with the guide in order to fix them as well as prepare yourself for v5 release which will make it required. v4 upgrade guide.

Walkthrough

Once the library is installed, the session service can be injected wherever needed in the application. In order to display login/logout buttons depending on the current session state, inject the service into the respective controller or component and query its isAuthenticated property in the template:

// app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default class ApplicationController extends Controller {
  @service session;

  
}
{{!-- app/templates/application.hbs --}}
<div class="menu">
  …
  {{#if this.session.isAuthenticated}}
    <a {{on "click" this.invalidateSession}}>Logout</a>
  {{else}}
    {{#link-to 'login'}}Login{{/link-to}}
  {{/if}}
</div>
<div class="main">
  {{outlet}}
</div>

In the invalidateSession action call the session service's invalidate method to invalidate the session and log the user out:

// app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from "@ember/object";

export default class ApplicationController extends Controller {
  @service session;

  

  @action
  invalidateSession() {
    this.session.invalidate();
  }
}

For authenticating the session, the session service provides the authenticate method that takes the name of the authenticator to use as well as other arguments depending on specific authenticator used. To define an authenticator, add a new file in app/authenticators and extend one of the authenticators the library comes with, e.g.:

// app/authenticators/oauth2.js
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default class OAuth2Authenticator extends OAuth2PasswordGrant {}

With that authenticator and a login form like

{{!-- app/templates/login.hbs --}}
<form {{on "submit" this.authenticate}}>
  <label for="identification">Login</label>
  <input id='identification' placeholder="Enter Login" value={{this.identification}} {{on "change" this.updateIdentification}}>
  <label for="password">Password</label>
  <input id='password' placeholder="Enter Password" value={{this.password}} {{on "change" this.updatePassword}}>
  <button type="submit">Login</button>
  {{#if this.errorMessage}}
    <p>{{this.errorMessage}}</p>
  {{/if}}
</form>

the session can be authenticated with the session service's authenticate method:

// app/controllers/login.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from "@ember/object";
import { tracked } from "@glimmer/tracking";

export default class LoginController extends Controller {
  @tracked errorMessage;
  @service session;

  @action
  async authenticate(e) {
    e.preventDefault();
    let { identification, password } = this;
    try {
      await this.session.authenticate('authenticator:oauth2', identification, password);
    } catch(error) {
      this.errorMessage = error.error || error;
    }

    if (this.session.isAuthenticated) {
      // What to do with all this success?
    }
  }

  @action
  updateIdentification(e) {
    this.identification = e.target.value;
  }

  @action
  updatePassword(e) {
    this.password = e.target.value;
  }
}

To make a route in the application accessible only when the session is authenticated, call the session service's requireAuthentication method in the respective route's beforeModel method:

// app/routes/authenticated.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class AuthenticatedRoute extends Route {
  @service session;

  beforeModel(transition) {
    this.session.requireAuthentication(transition, 'login');
  }
}

This will make the route (and all of its subroutes) transition to the login route if the session is not authenticated. Add the login route in the router like this:

// app/router.js
Router.map(function() {
  this.route('login');
});

It is recommended to nest all of an application's routes that require the session to be authenticated under a common parent route:

// app/router.js
Router.map(function() {
  this.route('login');
  this.route('authenticated', { path: '' }, function() {
    // all routes that require the session to be authenticated
  });
});

To prevent a route from being accessed when the session is authenticated (which makes sense for login and registration routes for example), call the session service's prohibitAuthentication method in the respective route's beforeModel method:

// app/routes/login.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class LoginRoute extends Route {
  @service session;

  beforeModel(transition) {
    this.get('session').prohibitAuthentication('index');
  }
}

The session service also provides the handleAuthentication and handleInvalidation methods for handling authentication and invalidation of the session (which not only happens when the user submits the login form or clicks the logout button but also when the session is authenticated or invalidated in another tab or window of the application). The handleAuthentication method will transition to a configurable route while the handleInvalidation method will reload the page to clear all potentially sensitive data from memory. In order to customize those behaviours, these methods can be overridden when the application defines its own session service that extends the one provided by Ember Simple Auth.

To add authorization information to requests, you can use the session service to check if the session is authenticated and access authentication/authorization data, e.g. a token:

// app/adapters/application.js
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';

export default class ApplicationAdapter extends JSONAPIAdapter {
  @service session;

  @computed('session.{data.authenticated.access_token,isAuthenticated}')
  get headers() {
    let headers = {};
    if (this.session.isAuthenticated) {
      // OAuth 2
      headers['Authorization'] = `Bearer ${this.session.data.authenticated.access_token}`;
    }

    return headers;
  }
}

The Session Service

The session service is the main interface to the library. It defines the authenticate, invalidate and authorize methods as well as the session events as shown above.

It also provides the isAuthenticated as well as the data properties. The latter can be used to get and set the session data. While the special authenticated section in the session data contains the data that was acquired by the authenticator when it authenticated the session and is read-only, all other session data can be written and will also remain in the session after it is invalidated. It can be used to store all kinds of client side data that needs to be persisted and synchronized across tabs and windows, e.g.:

this.session.set('data.locale', 'de');

Authenticators

Authenticators implement the concrete steps necessary to authenticate the session. An application can leverage several authenticators for different kinds of authentication mechanisms (e.g. the application's own backend server, external authentication providers like Facebook etc.) while the session is only ever authenticated with one authenticator at a time. The authenticator to use is chosen when authentication is triggered via the name it is registered with in the Ember container:

this.session.authenticate('authenticator:some');

Ember Simple Auth comes with 4 authenticators:

To use any of these authenticators in an application, define a new authenticator in app/authenticators, extend if from the Ember Simple Auth authenticator

// app/authenticators/oauth2.js
import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default class OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator {}

and invoke the session service's authenticate method with the respective name, specifying more arguments as needed by the authenticator:

this.session.authenticate('authenticator:some', data);

Customizing an Authenticator

Authenticators are easily customized by setting the respective properties, e.g.:

// app/authenticators/oauth2.js
import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default class OAuth2Authenticator extends OAuth2PasswordGrantAuthenticator {
  serverTokenEndpoint = '/custom/endpoint';
}

Implementing a custom Authenticator

Besides extending one of the predefined authenticators, an application can also implement fully custom authenticators. In order to do that, extend the abstract base authenticator that Ember Simple Auth comes with and override the authenticate, restore and (optionally) invalidate methods:

// app/authenticators/custom.js
import Base from 'ember-simple-auth/authenticators/base';

export default class CustomAuthenticator extends Base {
  restore(data) {
    
  }

  authenticate(options) {
    
  }

  invalidate(data) {
    
  }
}

Session Stores

Ember Simple Auth persists the session state via a session store so it survives page reloads. There is only one store per application that can be defined in app/session-stores/application.js:

// app/session-stores/application.js
import Cookie from 'ember-simple-auth/session-stores/cookie';

export default class ApplicationSessionStore extends Cookie {}

If the application does not define a session store, the adaptive store which uses localStorage if that is available or a cookie if it is not, will be used by default. To customize the adaptive store, define a custom store in app/session-stores/application.js that extends it and overrides the properties to customize.

Store Types

Ember Simple Auth comes with 4 stores:

Adaptive Store

The adaptive store stores its data in the browser's localStorage if that is available or in a cookie if it is not; this is the default store.

localStorage Store

The localStorage store stores its data in the browser's localStorage. This is used by the adaptive store if localStorage is available.

Cookie Store

The Cookie store stores its data in a cookie. This is used by the adaptive store if localStorage is not available. This store must be used when the application uses FastBoot.

sessionStorage Store

The sessionStorage store stores its data in the browser's sessionStorage. See the Web Storage docs for details on sessionStorage and localStorage. caniuse has up-to-date information on browser support of sessionStorage and localStorage.

Ephemeral Store

The ephemeral store stores its data in memory and thus is not actually persistent. This store is mainly useful for testing. Also the ephemeral store cannot keep multiple tabs or windows in sync as tabs/windows cannot share memory.

Customizing the Store

The session store is easily customized by setting the respective properties, e.g.:

// app/session-stores/application.js
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';

export default class ApplicationSessionStore extends AdaptiveStore {
  cookieName = 'my-apps-session-cookie';
}

Implementing a custom Store

Besides using one of the predefined session stores, an application can also implement fully custom stores. In order to do that, extend the abstract base session store that Ember Simple Auth comes with and implement the persist, restore and clear methods:

// app/session-stores/application.js
import Base from 'ember-simple-auth/session-stores/base';

export default class ApplicationSessionStore extends Base {
  persist() {
    
  }

  restore() {
    
  }
}

FastBoot

Ember Simple Auth works with FastBoot out of the box as long as the Cookie session store is being used. In order to enable the cookie store, define it as the application store:

// app/session-stores/application.js
import CookieStore from 'ember-simple-auth/session-stores/cookie';

export default class ApplicationSessionStore extends CookieStore {}

If you are using the OAuth2PasswordGrantAuthenticator, or DeviseAuthenticator, you must add node-fetch to your list of FastBoot whitelisted dependencies in package.json:

{
  "fastbootDependencies": [
    "node-fetch"
  ]
}

Engines

Ember Simple Auth works with engines out of the box. The host app and any engine(s) share the same session service so they can synchronize the authentication status:

// my-engine/addon/routes/index.js
import Application from '@ember/application';
import loadInitializers from 'ember-load-initializers';

class App extends Application {
  

  engines = {
    'my-engine': {
      dependencies: {
        services: [
          'session'
        ]
      }
    }
  }
});



export default App;

The session can then be authenticated or invalidated from the host app or any of the engines and the state will be synchronized via the service.

One thing to be aware of is that if the authentication route is outside of the engine (e.g. in the host app), it is necessary to use the special transitionToExternal method in the engine to transition to it. That can be done by passing a callback instead of a route name to the session service's requireAuthentication method in that case:

// my-engine/addon/routes/index.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class IndexRoute extends Route {
  @service session;

  beforeModel(transition) {
    this.get('session').requireAuthentication(transition, () => this.transitionToExternal('login'));
  },
}

Testing

Ember Simple Auth comes with a set of test helpers that can be used in acceptance tests.

Our helpers use the more modern testing syntax and therefore require ember-cli-qunit 4.2.0 or greater or ember-qunit 3.2.0 or greater.

We provide the following helpers:

  • currentSession() returns the current session.
  • authenticateSession(sessionData) authenticates the session asynchronously; the optional sessionData argument can be used to mock the response of an authentication request, to provide a specific authorization token or user data.
  • invalidateSession() invalidates the session asynchronously.

Which can be used as shown in the following example:

import { module, test } from 'qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { currentSession, authenticateSession, invalidateSession } from 'ember-simple-auth/test-support';

module('Acceptance | app test', function(hooks) {
  setupApplicationTest(hooks);

  test('/login redirects to index if user is alread logged in', async function(assert) {
    await authenticateSession({
      authToken: '12345',
      otherData: 'some-data'
    });
    await visit('/login');

    assert.equal(currentURL(), '/');

    let sessionData = currentSession().get('data.authenticated');
    assert.equal(sessionData.authToken, '12345');
    assert.equal(sessionData.otherData, 'some-data');
  });

  test('/protected redirects to /login if user is not logged in', async function(assert) {
    await invalidateSession();

    await visit('/protected');

    assert.equal(currentURL(), '/login');
  });
});

If you're an ember-mocha user, we can recommend to check out this example from the test suite of ember-simple-auth itself.

Other guides

License

Ember Simple Auth is developed by and © Mainmatter GmbH and contributors. It is released under the MIT License.

Ember Simple Auth is not an official part of Ember.js and is not maintained by the Ember.js Core Team.

ember-simple-auth's People

Contributors

bakura10 avatar bbooth avatar bobrimperator avatar briarsweetbriar avatar candunaj avatar constantm avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar exelord avatar f3ndot avatar fsmanuel avatar geekygrappler avatar greenkeeper[bot] avatar heroiceric avatar jayjayjpg avatar kbullaughey avatar marcoow avatar mike-north avatar msalahz avatar muziejus avatar peterchoo avatar quaertym avatar renovate[bot] avatar romulomachado avatar snewcomer avatar srvance avatar stevenwu avatar turbo87 avatar ugisozols avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-simple-auth's Issues

Item gets saved but doesn't show up while listing

I've setup the plugin and it works.

And I've the following Achievement route which finds all the items from the rails server.

App.AchievementsRoute = Ember.Route.extend
  model: -> App.Achievement.find()

Now, if I add the following to protect this route:

App.AchievementsRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin)

The data gets saved but the list is empty.
Does this mixin looks for something like current_user kind of association?
The Achievement model in the rails side is user association free, it doesn't have any associations at all.
If I remove the Ember.SimpleAuth.AuthenticatedRouteMixin, all the items show up.

Token request does not properly encode special characters in username/password

If a username or password contains special url characters, such as an ampersand, it breaks the url encoding as these characters are not properly escaped.

For example, this password:

onetwo&three

would be passed to the server as:

{
   password: onetwo,
   three: null
}

Rather than creating the querystring, it would be better to create a simple object in tokenRequestOptions and let jQuery handle the details.

Access to the current logged in user

Hi I was just wondering if you could help me by recommending the best way to gain access to the currently logged in user site wide so as I can use something like this in templates {{currentUser.name}} ?

I have the token based authentication working fine using ember-appkit-rails and also has_secure_password I'm just unsure of the correct way to approach this.

Any help is greatly appreciated!

Does ember-simple-auth work with Devise?

Hi,

I noticed in your list of "Middleware supporting RFC 6749", there is no mention of devise, the popular Rails Auth system by Plataformatec.

So i wanted to know if ember-simple-auth can work with that system as well?

Thanks!

Support for Ember-Model

How difficult is it to support this for Ember-Model? How about making it generic and can be used with any data drivers?

LoginControllerMixin: tokenRequestOptions ambiguous double testing client_id being empty

I was reading through the LoginControllerMixin and found this ambiguous part:

    if (!Ember.isEmpty(client_id)) {
      postData.push('client_id=' + client_id);
      if (!Ember.isEmpty(client_id)) {
        postData.push('client_secret=' + client_secret);
      }
    }

Inside the first test for client_id being empty it is tested again.
Was the intention to check for client_secret being Empty?
Or am I missing something here?

All routes Authenticated

Hi!

Is there a way to set all routes as authenticated ?

I've tried to add both Ember.SimpleAuth.ApplicationRouteMixin and Ember.SimpleAuth.AuthenticatedRouteMixin to my application route but there's an infinite loop to login page, which is itself authenticated...

Changing Ember.SimpleAuth.AuthenticatedRouteMixin#beforeModel like this seems to work but I don't feel this to be robust enough:

  beforeModel: function(transition) {
    if (!this.get('session.isAuthenticated') && transition.targetName != 'login') {
      transition.abort();
      this.triggerLogin(transition);
    }
  },

Token invalidation not handled

If the server invalidates the token, a 401 will be returned by the server on request. We need to somehow catch this, reset the session and redirect to login.

Issue with testing

We've been having problems with unit tests. The test was fairly straight forward:

test("Login, render dashboard", function() {
  expect(1);
  visit("/user/login");
  fillIn("#identification","test");
  fillIn("#password","test");
  click("#btnLogin");
  andThen( function() {
    equal(find(".island").length, 4, "Multiple islands should be rendered");
  });
});

And the result in the console was:

Assertion failed: You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in an Ember.run

In the debugger, we stepped through jQuery where it executes callbacks for AJAX responses. Eventually we found it. We needed to wrap your functionality with Ember.run() in your login function. This is around like 439 of ember-simple-auth.js in version 0.0.9.

Ember.run(function() {
  _this.get('session').setup(response);
  _this.send('loginSucceeded');
});

This has fixed the issue! Thought you should know.

Regards.

Allow for full page load on logout

Right now the routeAfterLogout field lets you specify a route to go to using transitionToRoute when logout is performed. However, if you are using something like Ember Data you may want to guarantee that the data cache is also cleared on logout, just in case the user immediately logs in again. To have this happen in my own app I overrode the logout action like this:

logout: function () {
    var token = this.get('session.authToken');
    jQuery.ajax({
        url: apiEndpoint + '/users/auth/logout?authToken=' + token,
        type: 'GET'
    });
    this.get('session').destroy();
    location.href = './';
}

The important part for this ticket is the last line where we actually navigate to the root of the application as opposed to going to the home route through Ember. The other part allowing me to invalidate my session token on the server side is also probably a worthwhile addition.

Uncaught TypeError: Cannot call method 'register' of undefined

Trying to setup with Ember app and as soon as I write:

Ember.Application.initializer
  name: "authentication"
  initialize: (container, application) ->
    Ember.SimpleAuth.setup application

I get the error:

Uncaught TypeError: Cannot call method 'register' of undefined

Following is the console trace:

DEBUG: ------------------------------- ember.js?body=1:3231
DEBUG: Ember      : 1.2.0 ember.js?body=1:3231
DEBUG: Handlebars : 1.1.2 ember.js?body=1:3231
DEBUG: jQuery     : 1.10.2 ember.js?body=1:3231
DEBUG: ------------------------------- ember.js?body=1:3231
event.returnValue is deprecated. Please use the standard event.preventDefault() instead. jquery.js?body=1:5375
Uncaught TypeError: Cannot call method 'register' of undefined ember-simple-auth.js?body=1:52
Ember.SimpleAuth.setup ember-simple-auth.js?body=1:52
Ember.Application.initializer.initialize tagliners.js?body=1:5
(anonymous function) ember.js?body=1:36617
visit ember.js?body=1:35638
DAG.topsort ember.js?body=1:35692
Ember.Application.Ember.Namespace.extend.runInitializers ember.js?body=1:36614
Ember.Application.Ember.Namespace.extend._initialize ember.js?body=1:36499
Backburner.run ember.js?body=1:5716
Ember.run ember.js?body=1:6082
(anonymous function) ember.js?body=1:36364
fire jquery.js?body=1:3049
self.fireWith jquery.js?body=1:3161
jQuery.extend.ready jquery.js?body=1:434
completed jquery.js?body=1:105

setup Travis CI build

  • all jquery versions that ember supports
  • all relevant ember/ember-data/handlebars versions

Create logout route

Hi,

In the strategies branch, currently the way to handle login / logout link is:

{{#if session.isAuthenticated }}
    <a href="#" {{ action 'invalidateSession' }}>Logout</a>
{{else}}
    <a href="#" {{ action 'authenticateSession' }}>Login</a>
{{/if}}

However this seems like a bad approach and we should use {{#link-to}} because without using the link-to helper, we don't have anymore the automatic "active" class added.

Update library to an OAuth 2.0 Spec

This looks like a great library! Can I make a suggestion?

I know the current token is based on an RFC spec that never made it.

I think it might be worth upgrading to an OAuth2.0 type authentication. It offers multiple grant types, one of which (Resource Owner Password Credentials Grant) is basically the same as what you have now.

The client sends their username and password and gets granted with an access token.

Its pretty much the same as what you have but follows a spec. It might save people time in the future as the chances are code is already available for their platform.
For example we use this excellent PHP library that has support built in already.

Sign up example

I looked at your ember simple auth examples, but I could not see anything documenting best practices for a sign-up user flow. Is there any documentation on recommended practices for a sign-up user flow?

Session data doesn't last past closing the browser tab

When the user is logged in, the session lasts throughout the application even when refreshing the page. When the browser tab is closed, the session dies and does not continue when re-opening the page.

It also doesn't last if you open a link in a new tab/window - the sessions seems to be specific to that tab instance.

Is this intentional or a bug?

Testing?

How exactly do you go about testing this within an Ember app?

Is there a way to fake server calls, or just force it to log in with fake data?

Cross domain authorization

It might be necessary to send the Authorization header cross-domain in some scenarios (when the data API is on a different domain than the one the page is loaded from). There should be the option to whitelist certain domains so that the Authorization header would also be included in requests to those.

There also seems to be a problem in the cross-domain case that might be caused by Ember.SimpleAuth: http://stackoverflow.com/questions/19755570/http-headers-setting-authorization-header-stops-data-from-loading/19773241#19773241

Request content-type is not json

content-type is set to form-urlencoded

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:32
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:5000
Origin:http://localhost:5000
Pragma:no-cache
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest

Bug if app is entered through a protected route

If I load the application on a non-protected route and then transition to a protected route, everything works normally.

However, when I load the application on the protected route, it throws the following error:

screen shot 2013-10-29 at 15 55 57

I also created a couple of jsbins:

JSbin for working example
JSbin for failing example

Unfortunately the error can not be seen in JSBin hence the screenshot. I checked this both with ember-1.0.0 and the latest canary build.

RFC : phonegap support

Hi, I'm using a modified version of this library in a phonegap application. Works fine. You might be interested to have this merged into the code base.

My hack involves moving the persistence to local storage when available.

If your interested I'l proceed with a PR.

A different approach might work be preferred : use cookies unless the protocol is file:// (or not http:// and not https://) and localStorage is available.

The difference is 'use cookies unless not http(s)' vs 'use localStorage unless not present'

What do you think?

CSRF?

Hi there,

If you are storing auth token information in a cookie, I'm just wondering if this is strong enough to prevent CSRF.

Is this safe because the cookie alone does not allow authentication? (A client script needs to attach the token to a HTTP header)

Loading/error substates

I've got Ember.SimpleAuth working well, thanks for creating such a great library!

One thing I've noticed is upon clicking "Login", there is no visible loading icon/screen and no error handling.

I'm not sure if there is an option to implement this already, but maybe we could make use of the Ember Loading and Error substates?

serverTokenEndpoint in setup function removed?

In the previous version I was able to overwrite the serverTokenEndpoint in the setup function.
This feature seems to be missing in the latest version.

Due to this I implemented it like this:

Ember.SimpleAuth.Authenticators.OAuth2 = Ember.SimpleAuth.Authenticators.OAuth2.reopen({
    serverTokenEndpoint: '/api/login'
});

Is this intentional?

routerAfterInvalidation doesn't work properly

I'm not sure if it's ember-simple-auth bug.
Let's say we have index route:

   App.IndexRoute = Ember.Route.extend({
        redirect: function() {
            this.transitionTo('reports');
        }
    });

and 'reports' route has AuthenticatedRouteMixin
If we logout from 'reports' route it doesn't show login page - it still shows 'reports'.

AuthenticatedRouteMixin: replace beforeModel by willTransition

Hi,

I've noticed that beforeModel is not systematically called (manual URL change for example) and it would be better to trigger login from the willTransition route action, wich is actually called for each transition.

Is that something you would aggree a PR for ?

Wrong check in LoginControllerMixin?

I might be totally wrong here, but if I am then it would be nice if someone could explain the logic.

This line of code in Ember.SimpleAuth.LoginControllerMixin is currently part of this:

if (!Ember.isEmpty(client_id)) {
  postData.push('client_id=' + client_id);
  if (!Ember.isEmpty(client_id)) {
    postData.push('client_secret=' + client_secret);
  }
}

Shouldn't it be this?

if (!Ember.isEmpty(client_id)) {
  postData.push('client_id=' + client_id);
  if (!Ember.isEmpty(client_secret)) {
    postData.push('client_secret=' + client_secret);
  }
}

It just seems a bit redundant to check client_id twice and then not use it in the block, while at the same time just assume that client_secret is present as long as client_id is. Again, please enlighten me - I'm new to this.

cleanup examples

  • reuse stuff in the Rack apps (make one Rack app that serves all examples)
  • add some comments that explain what's done and why

Example usage or integration for non-Rails folks? (EAK perhaps)

Hey I love the work on this as I think it is such an important part of the Ember ecosystem. keep up the awesome work!

I am not a Rails guy and I am building an application using Ember-App-Kit. Any chance for an integration and usage example for EAK or at least for people who dont have (or perhaps want) rails installed in order to use it?

I assume in EAK I would just merge Core and Session into one file in the /app/helpers folder and then put the mixins under /app/mixins and then import the mixins where I will need to use them.

Any thoughts or suggestions?

Bug when using new strategy

Hi,

I'm trying to use the new strategies branch, however I'm encountering an error:

TypeError: 'null' is not an object (evaluating 'this.get('authenticator').create')

It seems I've followed the example. As JS is not my primary language I'm not sure to be able to spot where the problem comes from.

Thanks!

QUnit integration test hangs during route transition

ember-simple-auth config:

App.initializer({

  initialize: function(container, application) {
    Ember.SimpleAuth.setup(container, application, {
      loginRoute: 'user.login',
      routeAfterLogin: '/user/dashboard',
      routeAfterLogout: '/user/login',
      serverTokenEndpoint: '/api/token',
    });
  }
});

The Test:

test("Visit login page", function() {
  expect(1);
  visit("/user/login");
  andThen(function() {
    ok(true);
   });
});

The problem:

The test hangs during the route transition.

DEBUG: 'DEBUG: -------------------------------'
DEBUG: 'DEBUG: Ember      : 1.2.0-beta.3'
DEBUG: 'DEBUG: Ember Data : 1.0.0-beta.2'
DEBUG: 'DEBUG: Handlebars : 1.1.2'
DEBUG: 'DEBUG: jQuery     : 1.9.1'
DEBUG: 'DEBUG: -------------------------------'
INFO: 'generated -> route:user', Object{fullName: 'route:user'}
INFO: 'Rendering application with default view <appkit@view:toplevel::ember296>', Object{fullName: 'view:application'}
INFO: 'generated -> controller:user', Object{fullName: 'controller:user'}
INFO: 'Rendering user with default view <appkit@view:default::ember317>', Object{fullName: 'view:user'}
INFO: 'Rendering user.login with default view <appkit@view:default::ember329>', Object{fullName: 'view:user.login'}
LOG: 'Transitioned into 'user.login''
INFO: 'generated -> route:user', Object{fullName: 'route:user'}
INFO: 'Rendering application with default view <appkit@view:toplevel::ember398>', Object{fullName: 'view:application'}
INFO: 'generated -> controller:user', Object{fullName: 'controller:user'}
INFO: 'Rendering user with default view <appkit@view:default::ember416>', Object{fullName: 'view:user'}
INFO: 'Rendering user.login with default view <appkit@view:default::ember422>', Object{fullName: 'view:user.login'}
LOG: 'Transitioned into 'user.login''
LOG: 'Transitioned into 'user.login''

Hangs right here

The test will finish if I override the init function in simple-auth and strip out the body of that function. I think maybe there is an async call in init that isn't resolving or something?

Other than this test failing, ember-simple-auth is working as expected. All protected routes require login and the session object is being returned correctly.

FYI this is within an ember app kit project.

Documentation for Rails developers (and other server-side frameworks!)

It would be wonderful to have documentation on how to use this library with Rails. I haven't started trying to add authentication to the Rails+Ember app I'm building, and I'd love to get a hint about the right direction to go in. If you have any code snippets or general words of advice to get me started, I'd be happy to write up the documentation in the wiki myself when I figure it all out.

Send user identifier along with the bearer token

I think it might be more secure if the AJAX prefilter send the user identification (i.e. their email or username) along with the bearer token.

That way the server can look up the user both by email and access token, and seems to me like it would be more secure.

Does ember-simple-auth work with Devise?

Hi,

I noticed in your list of "Middleware supporting RFC 6749", there is no mention of devise, the popular Rails Auth system by Plataformatec.

So i wanted to know if ember-simple-auth can work with that system as well?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.