Code Monkey home page Code Monkey logo

satellizer's Introduction

Project Logo

Donate Join the chat at https://gitter.im/sahat/satellizer Build Status npm version Book session on Codementor OpenCollective OpenCollective

Live Demo


Satellizer is a simple to use, end-to-end, token-based authentication module for AngularJS with built-in support for Google, Facebook, LinkedIn, Twitter, Instagram, GitHub, Bitbucket, Yahoo, Twitch, Microsoft (Windows Live) OAuth providers, as well as Email and Password sign-in. However, you are not limited to the sign-in options above, in fact you can add any OAuth 1.0 or OAuth 2.0 provider by passing provider-specific information in the app config block.

Screenshot

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]

Table of Contents

Installation

Browser

<script src="angular.js"></script>
<script src="satellizer.js"></script>
<!-- Satellizer CDN -->
<script src="https://cdn.jsdelivr.net/satellizer/0.15.5/satellizer.min.js"></script>

NPM

$ npm install satellizer

Bower

$ bower install satellizer

Requirements for Mobile Apps

With any Cordova mobile apps or any framework that uses Cordova, such as Ionic Framework, you will need to add cordova-plugin-inappbrowser plugin:

$ cordova plugin add cordova-plugin-inappbrowser

Make sure that inAppBrowser is listed in your project:

$ cordova plugins
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-device 1.1.1 "Device"
cordova-plugin-inappbrowser 1.3.0 "InAppBrowser"
cordova-plugin-splashscreen 3.2.0 "Splashscreen"
cordova-plugin-statusbar 2.1.1 "StatusBar"
cordova-plugin-whitelist 1.2.1 "Whitelist"
ionic-plugin-keyboard 1.0.8 "Keyboard"

Usage

Step 1. App Module

angular.module('MyApp', ['satellizer'])
  .config(function($authProvider) {

    $authProvider.facebook({
      clientId: 'Facebook App ID'
    });

    // Optional: For client-side use (Implicit Grant), set responseType to 'token' (default: 'code')
    $authProvider.facebook({
      clientId: 'Facebook App ID',
      responseType: 'token'
    });

    $authProvider.google({
      clientId: 'Google Client ID'
    });

    $authProvider.github({
      clientId: 'GitHub Client ID'
    });

    $authProvider.linkedin({
      clientId: 'LinkedIn Client ID'
    });

    $authProvider.instagram({
      clientId: 'Instagram Client ID'
    });

    $authProvider.yahoo({
      clientId: 'Yahoo Client ID / Consumer Key'
    });

    $authProvider.live({
      clientId: 'Microsoft Client ID'
    });

    $authProvider.twitch({
      clientId: 'Twitch Client ID'
    });

    $authProvider.bitbucket({
      clientId: 'Bitbucket Client ID'
    });

    $authProvider.spotify({
      clientId: 'Spotify Client ID'
    });

    // No additional setup required for Twitter

    $authProvider.oauth2({
      name: 'foursquare',
      url: '/auth/foursquare',
      clientId: 'Foursquare Client ID',
      redirectUri: window.location.origin,
      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate',
    });

  });

Step 2. Controller

angular.module('MyApp')
  .controller('LoginCtrl', function($scope, $auth) {

    $scope.authenticate = function(provider) {
      $auth.authenticate(provider);
    };

  });

Step 3. Template

<button ng-click="authenticate('facebook')">Sign in with Facebook</button>
<button ng-click="authenticate('google')">Sign in with Google</button>
<button ng-click="authenticate('github')">Sign in with GitHub</button>
<button ng-click="authenticate('linkedin')">Sign in with LinkedIn</button>
<button ng-click="authenticate('instagram')">Sign in with Instagram</button>
<button ng-click="authenticate('twitter')">Sign in with Twitter</button>
<button ng-click="authenticate('foursquare')">Sign in with Foursquare</button>
<button ng-click="authenticate('yahoo')">Sign in with Yahoo</button>
<button ng-click="authenticate('live')">Sign in with Windows Live</button>
<button ng-click="authenticate('twitch')">Sign in with Twitch</button>
<button ng-click="authenticate('bitbucket')">Sign in with Bitbucket</button>
<button ng-click="authenticate('spotify')">Sign in with Spotify</button>

Note: For server-side usage please refer to the examples directory.

Configuration

Below is a complete listing of all default configuration options.

$authProvider.httpInterceptor = function() { return true; },
$authProvider.withCredentials = false;
$authProvider.tokenRoot = null;
$authProvider.baseUrl = '/';
$authProvider.loginUrl = '/auth/login';
$authProvider.signupUrl = '/auth/signup';
$authProvider.unlinkUrl = '/auth/unlink/';
$authProvider.tokenName = 'token';
$authProvider.tokenPrefix = 'satellizer';
$authProvider.tokenHeader = 'Authorization';
$authProvider.tokenType = 'Bearer';
$authProvider.storageType = 'localStorage';

// Facebook
$authProvider.facebook({
  name: 'facebook',
  url: '/auth/facebook',
  authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
  redirectUri: window.location.origin + '/',
  requiredUrlParams: ['display', 'scope'],
  scope: ['email'],
  scopeDelimiter: ',',
  display: 'popup',
  oauthType: '2.0',
  popupOptions: { width: 580, height: 400 }
});

// Google
$authProvider.google({
  url: '/auth/google',
  authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
  redirectUri: window.location.origin,
  requiredUrlParams: ['scope'],
  optionalUrlParams: ['display'],
  scope: ['profile', 'email'],
  scopePrefix: 'openid',
  scopeDelimiter: ' ',
  display: 'popup',
  oauthType: '2.0',
  popupOptions: { width: 452, height: 633 }
});

// GitHub
$authProvider.github({
  url: '/auth/github',
  authorizationEndpoint: 'https://github.com/login/oauth/authorize',
  redirectUri: window.location.origin,
  optionalUrlParams: ['scope'],
  scope: ['user:email'],
  scopeDelimiter: ' ',
  oauthType: '2.0',
  popupOptions: { width: 1020, height: 618 }
});

// Instagram
$authProvider.instagram({
  name: 'instagram',
  url: '/auth/instagram',
  authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',
  redirectUri: window.location.origin,
  requiredUrlParams: ['scope'],
  scope: ['basic'],
  scopeDelimiter: '+',
  oauthType: '2.0'
});

// LinkedIn
$authProvider.linkedin({
  url: '/auth/linkedin',
  authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',
  redirectUri: window.location.origin,
  requiredUrlParams: ['state'],
  scope: ['r_emailaddress'],
  scopeDelimiter: ' ',
  state: 'STATE',
  oauthType: '2.0',
  popupOptions: { width: 527, height: 582 }
});

// Twitter
$authProvider.twitter({
  url: '/auth/twitter',
  authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
  redirectUri: window.location.origin,
  oauthType: '1.0',
  popupOptions: { width: 495, height: 645 }
});

// Twitch
$authProvider.twitch({
  url: '/auth/twitch',
  authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',
  redirectUri: window.location.origin,
  requiredUrlParams: ['scope'],
  scope: ['user_read'],
  scopeDelimiter: ' ',
  display: 'popup',
  oauthType: '2.0',
  popupOptions: { width: 500, height: 560 }
});

// Windows Live
$authProvider.live({
  url: '/auth/live',
  authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',
  redirectUri: window.location.origin,
  requiredUrlParams: ['display', 'scope'],
  scope: ['wl.emails'],
  scopeDelimiter: ' ',
  display: 'popup',
  oauthType: '2.0',
  popupOptions: { width: 500, height: 560 }
});

// Yahoo
$authProvider.yahoo({
  url: '/auth/yahoo',
  authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',
  redirectUri: window.location.origin,
  scope: [],
  scopeDelimiter: ',',
  oauthType: '2.0',
  popupOptions: { width: 559, height: 519 }
});

// Bitbucket
$authProvider.bitbucket({
  url: '/auth/bitbucket',
  authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',
  redirectUri: window.location.origin + '/',
  optionalUrlParams: ['scope'],
  scope: ['email'],
  scopeDelimiter: ' ',
  oauthType: '2.0',
  popupOptions: { width: 1020, height: 618 }
});

// Spotify
$authProvider.spotify({
  url: '/auth/spotify',
  authorizationEndpoint: 'https://accounts.spotify.com/authorize',
  redirectUri: window.location.origin,
  optionalUrlParams: ['state'],
  requiredUrlParams: ['scope'],
  scope: ['user-read-email'],
  scopePrefix: '',
  scopeDelimiter: ',',
  oauthType: '2.0',
  popupOptions: { width: 500, height: 530 }
});

// Generic OAuth 2.0
$authProvider.oauth2({
  name: null,
  url: null,
  clientId: null,
  redirectUri: null,
  authorizationEndpoint: null,
  defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],
  requiredUrlParams: null,
  optionalUrlParams: null,
  scope: null,
  scopePrefix: null,
  scopeDelimiter: null,
  state: null,
  oauthType: null,
  popupOptions: null,
  responseType: 'code',
  responseParams: {
    code: 'code',
    clientId: 'clientId',
    redirectUri: 'redirectUri'
  }
});

// Generic OAuth 1.0
$authProvider.oauth1({
  name: null,
  url: null,
  authorizationEndpoint: null,
  redirectUri: null,
  oauthType: null,
  popupOptions: null
});

Browser Support

9+ โœ“ โœ“ โœ“ โœ“ โœ“

Authentication Flow

Satellizer relies on token-based authentication using JSON Web Tokens instead of cookies.

Additionally, authorization (obtaining user's information with their permission) and authentication (application sign-in) requires sever-side implementation. See provided examples implemented in multiple languages for your convenience. In other words, you cannot just launch your AngularJS application and expect everything to work. The only exception is when you use OAuth 2.0 Implicit Grant (client-side) authorization by setting responseType: 'token' in provider's configuration.

Login with Email and Password

  1. Client: Enter your email and password into the login form.
  2. Client: On form submit call $auth.login() with email and password.
  3. Client: Send a POST request to /auth/login.
  4. Server: Check if email exists, if not - return 401.
  5. Server: Check if password is correct, if not - return 401.
  6. Server: Create a JSON Web Token and send it back to the client.
  7. Client: Parse the token and save it to Local Storage for subsequent use after page reload.

Login with OAuth 1.0

  1. Client: Open an empty popup window via $auth.authenticate('provider name').
  2. Client: Unlike OAuth 2.0, with OAuth 1.0 you cannot go directly to the authorization screen without a valid request_token.
  3. Client: The OAuth 1.0 flow starts with an empty POST request to /auth/provider.
  4. Server: Obtain and return request_tokenfor the authorization popup.
  5. Client: Set the URL location of a popup to the authorizationEndpoint with a valid request_token query parameter, as well as popup options for height and width. This will redirect a user to the authorization screen. After this point, the flow is very similar to OAuth 2.0.
  6. Client: Sign in with your username and password if necessary, then authorize the application.
  7. Client: Send a POST request back to the /auth/provider with oauth_token and oauth_verifier query parameters.
  8. Server: Do an OAuth-signed POST request to the /access_token URL since we now have oauth_token and oauth_verifier parameters.
  9. Server: Look up the user by their unique Provider ID. If user already exists, grab the existing user, otherwise create a new user account.
  10. Server: Create a JSON Web Token and send it back to the client.
  11. Client: Parse the token and save it to Local Storage for subsequent use after page reload.

Login with OAuth 2.0

  1. Client: Open a popup window via $auth.authenticate('provider name').
  2. Client: Sign in with that provider, if necessary, then authorize the application.
  3. Client: After successful authorization, the popup is redirected back to your app, e.g. http://localhost:3000, with the code (authorization code) query string parameter.
  4. Client: The code parameter is sent back to the parent window that opened the popup.
  5. Client: Parent window closes the popup and sends a POST request to /auth/provider withcode parameter.
  6. Server: Authorization code is exchanged for access token.
  7. Server: User information is retrived using the access token from Step 6.
  8. Server: Look up the user by their unique Provider ID. If user already exists, grab the existing user, otherwise create a new user account.
  9. Server: In both cases of Step 8, create a JSON Web Token and send it back to the client.
  10. Client: Parse the token and save it to Local Storage for subsequent use after page reload.

Log out

  1. Client: Remove token from Local Storage.

Note: To learn more about JSON Web Tokens visit JWT.io.

Obtaining OAuth Keys

- Visit [Google Developer Console](https://console.developers.google.com/iam-admin/projects) - Click **CREATE PROJECT** button - Enter *Project Name*, then click **CREATE** - Then select *APIs & auth* from the sidebar and click on *Credentials* tab - Click **CREATE NEW CLIENT ID** button - **Application Type**: Web Application - **Authorized Javascript origins**: *http://localhost:3000* - **Authorized redirect URI**: *http://localhost:3000*

Note: Make sure you have turned on Contacts API and Google+ API in the APIs tab.


- Visit [Facebook Developers](https://developers.facebook.com/) - Click **Apps > Create a New App** in the navigation bar - Enter *Display Name*, then choose a category, then click **Create app** - Click on *Settings* on the sidebar, then click **+ Add Platform** - Select **Website** - Enter *http://localhost:3000* for *Site URL*

- Sign in at [https://apps.twitter.com](https://apps.twitter.com/) - Click on **Create New App** - Enter your *Application Name*, *Description* and *Website* - For **Callback URL**: *http://127.0.0.1:3000* - Go to **Settings** tab - Under *Application Type* select **Read and Write** access - Check the box **Allow this application to be used to Sign in with Twitter** - Click **Update this Twitter's applications settings**

- Visit [Live Connect App Management](http://go.microsoft.com/fwlink/p/?LinkId=193157). - Click on **Create application** - Enter an *Application name*, then click on **I accept** button - Go to **API Settings** tab - Enter a *Redirect URL* - Click **Save** - Go to **App Settings** tab to get *Client ID* and *Client Secret*

Note: Microsoft does not consider localhost or 127.0.0.1 to be a valid URL. As a workaround for local development add 127.0.0.1 mylocalwebsite.net to /etc/hosts file and specify mylocalwebsite.net as your Redirect URL in the API Settings tab.

- Visit [https://github.com/settings/profile](https://github.com/settings/profile) - Select **Applications** in the left panel - Go to **Developer applications** tab, then click on the **Register new application** button - **Application name**: Your app name - **Homepage URL**: *http://localhost:3000* - **Authorization callback URL**: *http://localhost:3000* - Click on the **Register application** button

  • Visit https://developer.spotify.com
  • Select My Apps on the top menu
  • Select Create an App on the right side
  • Application Name: Your app name
  • Application Description: Your app Description
  • Click Create
  • Fill out the following:
  • Redirect URIs: http://localhost:3000
  • Click Save

API Reference

$auth.login(user, [options])

Sign in using Email and Password.

Parameters
Param Type Details
user Object JavaScript object containing user information.
options (optional) Object HTTP config object. See $http(config) docs.
Returns
  • response - The HTTP response object from the server.
Usage
var user = {
  email: $scope.email,
  password: $scope.password
};

$auth.login(user)
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });

$auth.signup(user, [options])

Create a new account with Email and Password.

Parameters
Param Type Details
user Object JavaScript object containing user information.
options (optional) Object HTTP config object. See $http(config) docs.
Returns
  • response - The HTTP response object from the server.
Usage
var user = {
  firstName: $scope.firstName,
  lastName: $scope.lastName,
  email: $scope.email,
  password: $scope.password
};

$auth.signup(user)
  .then(function(response) {
    // Redirect user here to login page or perhaps some other intermediate page
    // that requires email address verification before any other part of the site
    // can be accessed.
  })
  .catch(function(response) {
    // Handle errors here.
  });

$auth.authenticate(name, [userData])

Starts the OAuth 1.0 or the OAuth 2.0 authorization flow by opening a popup window. If used client side, responseType: "token" is required in the provider setup to get the actual access token.

Parameters
Param Type Details
name String One of the built-in or custom OAuth provider names created via $authProvider.oauth1() or $authProvider.oauth2().
userData (optional) Object If you need to send additional data to the server along with code, clientId and redirectUri (OAuth 2.0) or oauth_token and oauth_verifier (OAuth 1.0).
Returns
  • response - The HTTP response object from the server.
Usage
$auth.authenticate('google')
  .then(function(response) {
    // Signed in with Google.
  })
  .catch(function(response) {
    // Something went wrong.
  });

$auth.logout()

Deletes a token from Local Storage (or Session Storage).

Usage
$auth.logout();

$auth.isAuthenticated()

Checks authentication status of a user.

State True False
No token in Local Storage โœ“
Token present, but not a valid JWT โœ“
JWT present without exp โœ“
JWT present with exp and not expired โœ“
JWT present with exp and expired โœ“
Usage
// Controller
$scope.isAuthenticated = function() {
  return $auth.isAuthenticated();
};
<!-- Template -->
<ul ng-if="!isAuthenticated()">
  <li><a href="/login">Login</a></li>
  <li><a href="/signup">Sign up</a></li>
</ul>
<ul ng-if="isAuthenticated()">
  <li><a href="/logout">Logout</a></li>
</ul>

$auth.link(name, [userData])

Alias for $auth.authenticate(name, [userData]).

๐Ÿ’ก Note: Account linking (and merging) business logic is handled entirely on the server.

Usage
// Controller
$scope.link = function(provider) {
  $auth.link(provider)
    .then(function(response) {
      // You have successfully linked an account.
    })
    .catch(function(response) {
      // Handle errors here.
    });
};
<!-- Template -->
<button ng-click="link('facebook')">
  Connect Facebook Account
</button>

$auth.unlink(name, [options])

Unlinks an OAuth provider.

By default, sends a POST request to /auth/unlink with the { provider: name } data object.

Parameters
Param Type Details
name String One of the built-in or custom OAuth provider names created via $authProvider.oauth1() or $authProvider.oauth2().
options (optional) Object HTTP config object. See $http(config) docs.
Returns
  • response - The HTTP response object from the server.
Usage
$auth.unlink('github')
  .then(function(response) {
    // You have unlinked a GitHub account.
  })
  .catch(function(response) {
    // Handle errors here.
  });

$auth.getToken()

Returns a token from Local Storage (or Session Storage).

$auth.getToken();
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSJ9.kRkUHzvZMWXjgB4zkO3d6P1imkdp0ogebLuxnTCiYUU

$auth.getPayload()

Returns a JWT Claims Set, i.e. the middle part of a JSON Web Token.

Usage
$auth.getPayload();
// { exp: 1414978281, iat: 1413765081, userId: "544457a3eb129ee822a38fdd" }

$auth.setToken(token)

Saves a JWT or an access token to Local Storage / Session Storage.

Parameters
Param Type Details
token Object An object that takes a JWT (response.data[config.tokenName]) or an access token (response.access_token).

$auth.removeToken()

Removes a token from Local Storage / Session Storage. Used internally by $auth.logout().

Usage
$auth.removeToken();

$auth.setStorageType(type)

Sets storage type to Local Storage or Session Storage.

Parameters
Param Type Details
type String Accepts 'localStorage' and 'sessionStorage' values.
Usage
$auth.setStorageType('sessionStorage');

FAQ

โ“ How do I set offline_access?

$authProvider.google({
  optionalUrlParams: ['access_type'],
  accessType: 'offline'
});

โ“ Can I change redirectUri to something other than base URL?

By default, redirectUri is set to window.location.origin (protocol, hostname, port number of a URL) for all OAuth providers. This redirectUri must match exactly the URLยน specified in your OAuth app settings.

Facebook (example)

However, you can set redirectUri to any URL path you desire. For instance, you may follow the naming convention of Passport.js:

// Note: Must be absolute path.
window.location.origin + '/auth/facebook/facebook/callback'
window.location.origin + '/auth/facebook/google/callback'
...

Using the example above, a popup window will be redirected to http://localhost:3000/auth/facebook/callback?code=YOUR_AUTHORIZATION_CODE after a successful Facebook authorization. To avoid potential 404 errors, create server routes for each redirectUri URL that return 200 OK. Or alternatively, you may render a custom template with a loading spinner. For the moment, a popup will not stay long enough to see that custom template, due to 20ms interval polling, but in the future I may add support for overriding this polling interval value.

As far as Satellizer is concerned, it does not matter what is the value of redirectUri as long as it matches URL in your OAuth app settings. Satellizer's primary concern is to read URL query/hash parameters, then close a popup.

ยน Note: Depending on the OAuth provider, it may be called Site URL, Callback URL, Redirect URL, and so on.

โ“ How can I send a token in a format other than Authorization: Bearer <token>?

If you are unable to send a token to your server in the following format - Authorization: Bearer <token>, then use $authProvider.tokenHeader and $authProvider.tokenType config options to change the header format. The default values are Authorization and Bearer, respectively.

For example, if you need to use Authorization: Basic header, this is where you change it.

โ“ How can I avoid sending Authorization header on all HTTP requests?

By default, once user is authenticated, JWT will be sent on every request. If you would like to prevent that, you could use skipAuthorization option in your $http request. For example:

$http({
  method: 'GET',
  url: '/api/endpoint',
  skipAuthorization: true  // `Authorization: Bearer <token>` will not be sent on this request.
});

โ“ Is there a way to dynamically change localStorage to sessionStorage?

Yes, you can toggle between localStorage and sessionStorage via the following Satellizer methods:

  • $auth.setStorageType('sessionStorage');
  • $auth.setStorageType('localStorage');

โ“ I am having a problem with Ionic authentication on iOS 9.

First, check what kind of error you are getting by opening the Web Inspector from Develop > Simulator > index.html menu. If you have configured everything correctly, chances are you running into the following error:

Failed to load resource: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.

Follow instructions on this StackOverflow post by adding NSAppTransportSecurity to info.plist. That should fix the problem.

Community Resources

Tutorials

Credits

Contribution User
Dropwizard (Java) Example Alice Chen
Go Example Salim Alami
Ruby on Rails Example Simonas Gildutis
Ionic Framework Example Dimitris Bozelos

Additionally, I would like to thank all other contributors who have reported bugs, submitted pull requests and suggested new features!

License

The MIT License (MIT)

Copyright (c) 2016 Sahat Yalkabov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

satellizer's People

Contributors

aligit avatar amullins83 avatar celrenheit avatar chena avatar cridenour avatar dotch avatar elanper avatar elvece avatar foxandxss avatar gouroujo avatar graingert avatar greenkeeperio-bot avatar hilnius avatar iotaweb avatar krystalcode avatar m-kostira avatar marcbest avatar niemyjski avatar penoonan avatar petehouston avatar sabrehagen avatar sahat avatar sfwc avatar simonasdev avatar stevenceuppens avatar stuzl avatar tarex avatar theonetheonlydavidbrown avatar tymondesigns avatar viniciusdacal 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  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

satellizer's Issues

Add GitHub Provider

Would be nice to have an integrated GitHub provider in addition to all the provided ones.

Can we take a moment to examine this beauty?

This is from the README, once I saw this, my jaw literally dropped.

๐ŸŒŸ ๐ŸŒŸ ๐ŸŒŸ Props to you @sahat and all the contributers, where can I jump in? Im relatively new to Angular but I got the basics down.

angular.module('MyApp', ['Satellizer'])
  .config(function($authProvider) {

    $authProvider.facebook({
      clientId: '624059410963642',
    });

    $authProvider.google({
      clientId: '631036554609-v5hm2amv4pvico3asfi97f54sc51ji4o.apps.googleusercontent.com'
    });

    $authProvider.github({
      clientId: '0ba2600b1dbdb756688b'
    });

    $authProvider.linkedin({
      clientId: '77cw786yignpzj'
    });

    $authProvider.twitter({
      url: '/auth/twitter'
    });

    $authProvider.oauth2({
      name: 'foursquare',
      url: '/auth/foursquare',
      redirectUri: window.location.origin
      clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate',
    });

  });

Protected URLs, satellizer problem or not?

Seeing the route protected as a way to avoid access to protected routes, I am wondering if satellizer should care about that.

Let me explain:

Your implementation is cool, but as soon as I need different access levels (like user or admin) your implementation won't work. I mean, it is really for basic use cases.

In fact, your idea of "You can't access login / signup if you're logged in" is pretty much a specific use case. What if I want the user to access it and if logged in previously I want just to delete the old token?

What I want to say is that you could probably be safe deleting that last .run for both ngRouter and ui-router and let the developers create their own .run method with their own rules. That way you don't limit anyway to work with your use cases.

What do you think?

Considerations for refactoring?

Are there any plans to refactor satellizer.js into respective files for factories, providers, etc? Just curious if this is already in progress (as to avoid duplicate work). If not, are you interested in such a pull request?

Siantra and Rails Server

Hey @sahat, I saw you prepared rails-api server. If you want I can prepare for you pull request today or tomorrow.

I just want first to finish our provider side app which I already mostly did.

Or maybe you want to learn ruby and rails :)

parseUser ?

After facebook login

local.parseUser = function(token, deferred) {
var payload = JSON.parse(window.atob(token.split('.')[1]));
console.log(payload);
localStorage.setItem(config.tokenName, token);
$rootScope[config.user] = payload.user;

outputs:
{iss: "localhost", sub: "53fd16cd211929f8029a146f", iat: 1409097777032, exp: 1410307377032}

since payload.user is undefined, i always get $auth.isAuthenticated() === false
Altrough /api/me/ gives me the correct profile...

This happens on facebook login + express example - pretty much stock...
Any ideas of what I am doing wrong ?

PHP and Python code refactoring

@creminss It would be great if you could take a look at the PHP folder and see if you could refactor it. I don't know any PHP and this is my first time using Laravel writing that code. You have no doubt more experience with PHP than me so any contributions would be appreciated.

The game goes for Flask example. It is currently behind Node.js and PHP in that it does not support account linking and it still uses payload.user to store user object inside the token instead of payload.sub which only stores user's id.

Since I don't have much experience with Flask either, any code cleanup and refactoring would be nice. Especially refactoring some logic into config.py, database.py, models.py, etc.

Use your best judgement in both tasks.

Thanks for helping out! ๐Ÿ‘

false positives on 401

hey.

as in other libs i explored, it would make sense to actually filter for requests that require token.


scenario:

  • user logs in
  • user pulls data from our API (ret 200)
  • user pulls data from some other API (ret 401)
  • user gets logged out, despite the fact, that the request returning 401 was not from our API

ideally, during config, one could provide a function that would return true for requests / responses getting to/from our API, like:

function isAPI(config) {
  return /^https?\:\/\/(www\.)?example\.com/.test(config.url);
}

app.config(function ($authProvider) {
  $authProvider.requestFilter = isAPI;
  $authProvider.responseFilter = isAPI;
});

and the interceptor would check the config against this filter, like:

// ...
request: function(httpConfig) {
  var skip = angular.isFunction($authProvider.requestFilter) && !$authProvider.requestFilter(httpConfig);
  if (skip) {
    return httpConfig;
  }

  if (localStorage.getItem([config.tokenPrefix, config.tokenName].join('_'))) {
    httpConfig.headers.Authorization = 'Bearer ' + localStorage.getItem([config.tokenPrefix, config.tokenName].join('_'));
  }
  return httpConfig;
},
responseError : function (response) {
  var skip = angular.isFunction($authProvider.responseFilter) && !$authProvider.responseFilter(response.config);
  if (skip) {
    return $q.reject(rejection);
  }

  if (response.status === 401) {
    localStorage.removeItem([config.tokenPrefix, config.tokenName].join('_'));
  }
  return $q.reject(response);
}

Token key should be "access_token"

On this line:

local.parseUser(response.data.token, deferred);
,

Satellizer is expecting in the JSON response the token to be in the key token. However the spec says it should be access_token: http://tools.ietf.org/html/rfc6749#section-5.1

I am working with https://github.com/bshaffer/oauth2-server-php and it is highly configurable about anything including query keys, key names and others. However it does not allow configuring the keys of this particular response, because this is what the specification defines: https://github.com/bshaffer/oauth2-server-php/blob/6a30b9b67ae35c228e852109ed743bf34da22568/src/OAuth2/ResponseType/CryptoToken.php#L86-L91

I think Satellizer should respect the specification or at least provide a configuration about the token key to read from the data.

Fix promise resolutions

Right now, this code doesn't work in error scenarios:

$auth.authenticate(provider).then(
  function() {
    console.log('success');
  },
  function() {
    console.log('error');
  }
);

The error handler is never called because you are not properly rejecting failed promises. To make it easier, you should just use promise chaining.

Relevant changes to make my example code work:

$auth.authenticate = function(name) {
  var provider = (providers[name].type === '1.0') ? Oauth1 : Oauth2;
  return provider.open(providers[name]).then(function(response) {
    return Local.parseUser(response.token);
  });
};
local.parseUser = function(token) {
  var payload = JSON.parse($window.atob(token.split('.')[1]));
  $window.localStorage.jwtToken = token;
  $rootScope[config.user] = payload.user;
  $location.path(config.loginRedirect);
  return payload.user;
};
oauth2.open = function(options) {
  angular.extend(defaults, options);
  var url = oauth2.buildUrl();

  return Popup.open(url, defaults.popupOptions).then(function(oauthData) {
    return oauth2.exchangeForToken(oauthData).then(function(response) {
      return response.data;
    });
  });
};

I haven't tested against a success scenario but it should work fine - if you want, I can submit a PR changing all the promise code (and verify it works in various success and error scenarios too)

Incorrect requirements.txt

I think the jwt==0.3.1 should be PyJWT==0.2.1

The jwt module you currently have in there doesn't have the encode function you reference. They both install a jwt module that you import as jwt which is probably where the confusion came from.

Thanks for this project! I found it really useful.

Composed names on services is not a good idea.

Hey @sahat . You new convention of satellizer.foo to name the different services is not a good idea.

That only works with array notation like:

app.controller('foo', ['satellizer.Oauth2', function(Oauth2) {

}]);

but not with:

app.controller('foo', function(satellizer.Oauth2) {

});

For internal usage is ok because you are using the first mode, but if I want to override or decorate something, you are forcing me to use array notation.

I would think about our own prefix like: ss (s from sahat and s from stallizer) or even stl (satellizer).

ssOuath2, stlOauth2 or something like that.

What do you think?

Create a Storage service

So far we are using window.localStorage directly to store the token. That is ok, but not enough.

There is a common use case where you want to store the token in sessionStorage (to delete it when you close the browser). For example in a bank or any page with high security. You could even store the token in a cookie, nothing wrong.

So the thing is that we should abstract the storage into a service (repository pattern).

So there is a lot of different solutions, but since it is mostly local vs session, I vote to implement those two inside satellizer instead of giving the user the need of doing that.

I can't think atm about the best solution for us, but I open this issue to gather ideas.

Wrap login data in JSON object, Add token to header

Excuse my ignorance, am pretty new in Angular and I was wondering how could I send the login data wrapped in a JSON object instead of just email and password I want to send it like this developer: { email: ' ', password: ' '}

Another thing I'd like to know is how can I set the token and email to be sent in each request once signed in?

Thanks

POJO vs angular constant

I checked the source and I saw something I was curious about. Why did you decide to use a plain old js object instead of a angular constant? It could reduce the code (no need of that Object.defineProperties). You just need to wrap the config and providers in 1/2 configs.

You could leave the defineProperties to keep the same way of configuration or you could do:

angular.module('app').config(function(satellizer) {
   satellizer.loginUrl = "foo";
   satellizer.providers.google({ ... });
});

Or even two different configs, satellizer and satellizerProviders that is just personal preference.

Then you could inject that into $auth and Local so you don't have to wonder where that stuff comes from and would certainly help for unit testing.

It is up to you, I respect your decisions but this is more Angular-ish. (You're gonna hate me soon ;( )

Pop-up window is closing too fast (Firefox)

I checked Satellizer demo page on firefox and i notice that sometimes "provider pop-up" is closing too fast. Too fast closure does not allow the user to signin.
My super fast solution is to put some delay on $window.close() in RunBlock() function on line 392:

$timeout(function(){
  $window.close();
},5);

If anyone else noticed this error ?

Satellizer module name: lowercase or capitalized?

I have used capitalized module name Satellizer without giving it much thought. But before moving forward with broadcasting events and namespacing all internal services I need to pick one or the other convention.

It's a minor thing, but it is better to change it now in the 0.x stage rather after the 1.0 release.

Capitalized:

  1. Import.
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'Satellizer', 'mgcrea.ngStrap'])
  1. Events.
$scope.$on('Satellizer.loginSuccess', function(event) {

});
  1. Internal namespace.
.factory('Satellizer.Popup')
.factory('Satellizer.Oauth2')
.service('Satellizer.Utils')

Lowercase:

  1. Import.
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'satellizer', 'mgcrea.ngStrap'])
  1. Events.
$scope.$on('satellizer.loginSuccess', function(event) {

});
  1. Internal namespace.
.factory('satellizer.Popup')
.factory('satellizer.Oauth2')
.service('satellizer.Utils')

IE support

Do Satelizer support IE ?
Because i have problem when try to authorize on IE (11,10 or 9), after log-in in provider window the pop-up close and nothing else happend, user is still not log-in.

Stop catching 403 for login redirect

Hi.

Redirecting to the login page on 403 stops me from using 403 as it should be (Forbidden). It means that the user is not allowed to execute the given action on a resource. In that case I want to display an error message to the user not redirecting to the login page as that won't solve anything.

401 on the other hand means that the user is not authorized and it is thus OK to require a login.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Django REST framework oauth2

Hi sahat,

Great work on satellizer so far. Should you consider integrating oauth2 of django REST server?
You will need to modify the parseUser function to extract the returned token.
In django REST server (and other oauth2 providers), the value of the returned token is in 'access_token' key instead of 'token' key as in your server examples.

Example of the django REST framework is available at this page:
http://www.django-rest-framework.org/api-guide/authentication#oauth2authentication

Broken herokuapp example, idea for improvement

Hello,

I've looked at a few different auth seeds, and I really like yours, however in testing, I might have crashed your test site.

What I did was:

  • click login, auth with google
  • log out
  • click on the login again, auth with facebook
  • click on profile
  • try to link google (I saw a message popup with no text in the bottom right)
  • try to link facebook (another no-text message in the bottom right)
  • log out
  • try to register
  • site no longer responding

What I was trying to test, as it seems to be a common oversight, I often auth with a random service, and what I'd like to see is a seamless experience based on e-mail address.

So if I auth with google, it should know my e-mail address, and no matter what, the e-mail should always be verified. Once this happens, if I log out and try to login with facebook the next time, it should see that my e-mail is already registered, and ask me to authenticate with my e-mail / password, to ensure that the link is legitimate.

The next time, whether I choose google (linked with e-mail from first login) or facebook (linked with e-mail on second login) I would hope that I'd get a profile with both of these services linked.

If next time I choose github, I'd like the same thing, a verification of the e-mail/password to make sure I'm not trying to take someone's account when I don't own that e-mail, and once that's done, the profile should have all three linked + e-mail/pass.

--Cory

Forgot password flow?

LinkedIn Auth.

Hello,

Can you please help me with this problem : i'm trying to set-up linkedin auth and i get this message :
Invalid redirect_uri. This value must match a URL registered with the API Key.

From the configs i've seen that the redirect uri is windows.location.origin, but i guess linkedin is asking me for a real api like http://localhost:3000 (i'm using node).
My question is how should i get this going?:D

Thanks,
Alex

blank screen for facebook

I implemented all the example code and a blank window pops up from facebook (no option to authorize). Nothing hits the node.js server (no console.log from any route)

I pasted in my facebook appId and appSecret to the right places. I think I need additional config on the facebook side. Do I have to put a Site URL or something? I want to run the login locally as I don't have a domain name yet

Linking accounts

Is there some interest in adding functionality to link-up accounts?

example: I'm logged in by email/password or Facebook, and i like to add
LinkedIn as an alternative login-provider to my existing account.

I was thinking about the following methods:

  • link(name)
  • unlink(name)

On angular, we need to check that your only able to execute this methods once your logged-in.
On the server the corresponding api calls need to be protected.

Standardize provider scope as an array of strings

Facebook expects scope as a string with each scope separated by comma, where as some other providers like Google expect scope to be separated by space.

Provide a universal interface by using an array notation for all providers.

If setting your own custom OAuth provider, you can specify whether to use comma or space via the scopeDelimiter option.

Bower - concatenate, minify

Hi,

I'm trying to use Satellizer with yeoman/bower. I've added Satellizer to my application, run 'bower build' command and after opening the site in the browser:

Uncaught Error: [$injector:unpr] Unknown provider: aProvider <- a <- $http <- $compile

When i remove Satellizer then everything works correctly. From what i know, bower runs scripts to minify and concatenate files. If i disable this and include satellizer.js in "a normal way" everything works correctly as well. I guess that the code of Satellizer is not adapted to minify/concatenate. In the spare time i will try to check where the problem can be but maybe someone will fix this faster ;-)

Handling of (local only?) login failures is โ€ฆ lacking

If there is a real error on the back-end (e.g. status comes back as 501 or similar), there is no way of getting at that using $auth.login().catch(), since by then this information is long gone.

Also, if $auth.login() results in e.g. a 401 with message="Bad username or password", the interceptor quietly eats it and puts up the configured login page again. There is no feedback to the user that a login attempt was performed (and failed).

Only in the case that there is an error other than 401 and with JSON message attribute will there be a message displayed to the user.

currentUser on $rootScope

Hello!

I saw you're assigning currentUser on $rootScope which seems to be a very very common solution, but it is wrong. $rootScope shouldn't be used for that, it is a global variable and that is and always be wrong.

I suggest putting a auth.currentUser() or even a new service for the currentUser. Before you think that you need to inject that new service everywhere, you don't really need it that much, but even so, that is the Angular way.

What do you think? :)

Oauth2 Workflow

Hi!

We(@bslipek and I) want to build three example apps. One will be a sinatra oauth2 provider and second will be rails app with angular.js on frontend and rails on backend and third with sinatra on backend and angular.js on frontend.

Our Rails/Sinatra app will be authenticate users using satelizer and our custom provider.

This is our Oauth2 workflow right now.

1.Using Satellizer we get the code from provider. We send this code to our backend.
2. In backend using this code, secret key and other params we send an request to provider to get an access token.
3. Using this obtain access token we call '/me' action to get an uid, email and other user attributes from provider.
4. In the same action we parse the response body and we find or create user based on uid.
5. We are wondering about this step which should somehow set the user's authentication token.
a) store the provider access token in user database record.
b) generate new authentication token and change it on every request
6. Generate JWToken with user uid and token and send it back to satellizer.
7. Then on each request Satellizer include Bearer JWToken in header. After recive request our backend verify header token stored in database and call sing_in method in our case devise(sign_in, store: false) maybe in sinatra app we will use warden.

Of course we want to add these apps to satelizer example apps.

What do you think about this concept? Maybe we are missing something. These is our first oauth2 authentication implementation and we are worried about it.

Thanks for Your work! @sahat @lynndylanhurley

EDIT: I moved comment to new issue.

Security

I recently read this stack:
http://stackoverflow.com/questions/18605294/is-devises-token-authenticatable-secure

in short they say that auth tokens should:

  • changed after every request,
  • of cryptographic strength,
  • hashed using BCrypt (not stored in plain-text),
  • securely compared (to protect against timing attacks),
  • invalidated after 2 weeks (thus requiring users to login again)

But currently satellizer use the same token, and doesn't change token for the new one from request.
So @sahat what do you think? :)

Disable redirect after login/logout

Some applications may not have authentication on a separate page and the library shouldn't force a redirect after a successful login or logout. It should be possible through some value (null) of the loginRedirect and logoutRedirect configuration to disable this behavior.

For example, when I make a remote call which is not authenticated, I display the login partial the user and re-try the call that failed right away. This doesn't require the user to leave the page (and would destroy his work in doing so).

Node server module

Sahat,

I was thinking that it's maybe a good idea to develop a node-satellizer & express-satellizer middleware module, that hooks up most of the boilerplate code.

  • node-satellizer -> basic library with methods to exchange authorization codes etc.. this if someone wants to use satellizer with his own http derived framework like restify etc...
  • express-satellizer -> library on top of node-satelizer that hooks into express as middleware, and in which you just register your callback functions like signup user, find user, link, unlink, etc...

(for link, unlink -> see my previous issue)

If you like, i want to help on this.

Hardcoded redirect to /login

In the httpInterceptor there is a hardcoded redirect to /login.
$location.path('/login');

This should probably use the value from loginRoute in config

Demo broken

Hi!
Your demo page is currently broken:

Failed to load resource: the server responded with a status of 404 (Not Found) http://rawgit.com/sahat/satellizer/master/lib/satellizer.js

Dropping the $ on the services

Hello,

Just discovered this library. I have to say that it is plain awesome, really really love it. I am a big fan of JWT and this is a proper implementation (I have to dig into the code yet, but so far so good).

The only thing that bothers me is the service names. $ is reserved for angular services and we shouldn't use it. You can see more here.

You can read:

Do not use $ to prepend your own object properties and service identifiers. Consider this style of naming reserved by AngularJS and jQuery.

It is a pretty big BC, I just leave it for you to consider. If you decide to not change it, that is good for me too, I just pointed it :P

Keep this coming!

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.