Code Monkey home page Code Monkey logo

angular-oauth2's Introduction

angular-oauth2 Build Status

AngularJS OAuth2 authentication module written in ES6.

Currently angular-oauth2 only uses the Resouce Owner Password Credential Grant, i.e, using a credentials combination (username, password), we'll request an access token (using grant_type='password') which, in case of success, will typically return a response such as:

{
  "access_token": "foobar",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "foobiz"
}

Internally we'll automatically store it as a cookie and it will be used in every request adding an Authorization header: Authorization: 'Bearer foobar'.


Installation

Choose your preferred method:

  • Bower: bower install angular-oauth2
  • NPM: npm install --save angular-oauth2
  • Download: angular-oauth2

Usage

1. Download angular-oauth2 dependencies.

If you're using bower they will be automatically downloaded upon installing this library.

2. Include angular-oauth2 and dependencies.
<script src="<VENDOR_FOLDER>/angular/angular.min.js"></script>
<script src="<VENDOR_FOLDER>/angular-cookies/angular-cookies.min.js"></script>
<script src="<VENDOR_FOLDER>/query-string/query-string.js"></script>
<script src="<VENDOR_FOLDER>/angular-oauth2/dist/angular-oauth2.min.js"></script>
3. Configure OAuth (optional) and OAuthToken (optional):
angular.module('myApp', ['angular-oauth2'])
  .config(['OAuthProvider', function(OAuthProvider) {
    OAuthProvider.configure({
      baseUrl: 'https://api.website.com',
      clientId: 'CLIENT_ID',
      clientSecret: 'CLIENT_SECRET' // optional
    });
  }]);

You can also configure OAuth service in a .run() block, in case you retrieve the Oauth server configuration from a ajax request.

angular.module('myApp', ['angular-oauth2'])
  .run(['OAuth', function(OAuth) {
    OAuth.configure({
      baseUrl: 'https://api.website.com',
      clientId: 'CLIENT_ID',
      clientSecret: 'CLIENT_SECRET' // optional
    });
  }]);
4. Catch OAuth errors and do something with them (optional):
angular.module('myApp', ['angular-oauth2'])
  .run(['$rootScope', '$window', 'OAuth', function($rootScope, $window, OAuth) {
    $rootScope.$on('oauth:error', function(event, rejection) {
      // Ignore `invalid_grant` error - should be catched on `LoginController`.
      if ('invalid_grant' === rejection.data.error) {
        return;
      }

      // Refresh token when a `invalid_token` error occurs.
      if ('invalid_token' === rejection.data.error) {
        return OAuth.getRefreshToken();
      }

      // Redirect to `/login` with the `error_reason`.
      return $window.location.href = '/login?error_reason=' + rejection.data.error;
    });
  }]);

API

OAuthProvider

Configuration defaults:

OAuthProvider.configure({
  baseUrl: null,
  clientId: null,
  clientSecret: null,
  grantPath: '/oauth2/token',
  revokePath: '/oauth2/revoke'
});

OAuth

Update configuration defaults:

OAuth.configure({
  baseUrl: null,
  clientId: null,
  clientSecret: null,
  grantPath: '/oauth2/token',
  revokePath: '/oauth2/revoke'
});

Check authentication status:

/**
 * Verifies if the `user` is authenticated or not based on the `token`
 * cookie.
 *
 * @return {boolean}
 */

OAuth.isAuthenticated();

Get an access token:

/**
 * Retrieves the `access_token` and stores the `response.data` on cookies
 * using the `OAuthToken`.
 *
 * @param {object} user - Object with `username` and `password` properties.
 * @param {object} config - Optional configuration object sent to `POST`.
 * @return {promise} A response promise.
 */

OAuth.getAccessToken(user, options);

Refresh access token:

/**
 * Retrieves the `refresh_token` and stores the `response.data` on cookies
 * using the `OAuthToken`.
 *
 * @return {promise} A response promise.
 */

OAuth.getRefreshToken()

Revoke access token:

/**
 * Revokes the `token` and removes the stored `token` from cookies
 * using the `OAuthToken`.
 *
 * @return {promise} A response promise.
 */

OAuth.revokeToken()

NOTE: An event oauth:error will be sent everytime a responseError is emitted:

  • { status: 400, data: { error: 'invalid_request' }
  • { status: 400, data: { error: 'invalid_grant' }
  • { status: 401, data: { error: 'invalid_token' }
  • { status: 401, headers: { 'www-authenticate': 'Bearer realm="example"' } }

OAuthTokenProvider

OAuthTokenProvider uses angular-cookies to store the cookies. Check the available options.

Configuration defaults:

OAuthTokenProvider.configure({
  name: 'token',
  options: {
    secure: true
  }
});

OAuthToken

If you want to manage the token yourself you can use OAuthToken service. Please check the OAuthToken source code to see all the available methods.

Contributing & Development

Contribute

Found a bug or want to suggest something? Take a look first on the current and closed issues. If it is something new, please submit an issue.

Develop

It will be awesome if you can help us evolve angular-oauth2. Want to help?

  1. Fork it.
  2. npm install.
  3. Do your magic.
  4. Run the tests: gulp test.
  5. Build: gulp build
  6. Create a Pull Request.

The source files are written in ES6.

Reference

angular-oauth2's People

Contributors

adiramsalem avatar anteriovieira avatar erhardos avatar fixe avatar lionelb avatar nunofgs avatar pgom avatar rllola avatar ruipenso avatar timokasse avatar tinogomes 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

angular-oauth2's Issues

Add 401 Unauthorized response handling

According to the OAuth Bearer Token Usage spec, section 3.1 states that:

If the request lacks any authentication information (e.g., the client
was unaware that authentication is necessary or attempted using an
unsupported authentication method), the resource server SHOULD NOT
include an error code or other error information.

This library needs to handle receiving a 401 status code with no body.

Problem on module inject

I'm building a project with ionic framework.
When I inject 'angular-oauth2' on my root module I have this error:

Uncaught Error: [$injector:unpr] Unknown provider: $$cookieReaderProvider <- $$cookieReader <- $cookies <- OAuthToken <- oauthInterceptor <- $http <- $templateFactory <- $view <- $state <- $cookies

I tried with module angular-cookies from angular and with angular-cookie from ivpusic

NPM install fails

Hello,

# npm install --save angular-oauth2
npm WARN package.json [email protected] No description
npm WARN package.json [email protected] No README data
/
> [email protected] postinstall /Users/quozd/Development/test/node_modules/angular-oauth2
> ./node_modules/bower/bin/bower install

sh: ./node_modules/bower/bin/bower: No such file or directory
npm ERR! Darwin 14.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "--save" "angular-oauth2"
npm ERR! node v0.10.36
npm ERR! npm  v2.3.0
npm ERR! code ELIFECYCLE

npm ERR! [email protected] postinstall: `./node_modules/bower/bin/bower install`
npm ERR! Exit status 127
npm ERR! 
npm ERR! Failed at the [email protected] postinstall script './node_modules/bower/bin/bower install'.
npm ERR! This is most likely a problem with the angular-oauth2 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ./node_modules/bower/bin/bower install
npm ERR! You can get their info via:
npm ERR!     npm owner ls angular-oauth2
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/quozd/Development/test/npm-debug.log

Looks like installation is dependant on local bower files. Could you please fix this?

Revoking token should include token_type_hint in request body

According to https://tools.ietf.org/html/rfc7009, paragraph 2.1, a _"token_type_hint may be included in the body to help the authorization server to optimize the token lookup".
In OAuthProvider::revokeToken, if a refresh_token, it's passed as the token value. If not, the access_token value is set.
Could be helpful if the token_type_hint was added to the body and has, according to RFC, refresh_token or access_token value.

angular-oauth2 Module Error

when i add angular.module('myApp', ['angular-oauth2']) to my app, got
"Error: $injector:modulerr
Module Error
Failed to instantiate module"

AngularJS v1.3.15

Error in Readme file

You are missing the OAuth dependancy

.run(['$rootScope', '$window', function($rootScope, $window, OAuth) 

should be

.run(['$rootScope', '$window', 'OAuth', function($rootScope, $window, OAuth) 

Support for authorization code grant flow

I need to use this lib with an authorization API that implements the OAuth2 authorization code grant.
Quoting from [http://bshaffer.github.io/oauth2-server-php-docs/overview/grant-types/] :

The Authorization Code grant type is the most common OAuth2.0 flow. It implements 3-Legged OAuth and involves the user granting the client an authorization code, which can be exchanged for an Access Token.

Is this possible / achievable with the current release and do you have any suggestions on how to do it ?
Thank you.

Support for custom grant_type

Hi, is there a way to pass a custom grant_type instead of using the hardcoded grant_type: 'password'?
I have some additional rules on the server and I have created a custom grant type but I can't find a way to configure that. Thanks!

update oauth serverUrl after application start

Hello,
I plan to use your module, but after reading the doc, it seems that the only way to make it work is to configure it using a .config() block.
Unfortunatly, the app I work on can connect retrieve the oauth servers info at runtine, after application started.
Is there something I can achieve using your lib ?
Thanks.

Other Request Example

I am creating the both and oauth2 server side. From what I understand there is an intercepter which adds necessary headers for oauth2 request. The code is working fine when I do
OAuth.getAccessToken();
I get the access token and everything works as expected. but when I try to access resource I get error. This is the code

$http.get( SERVER_CONFIG.baseUrl +  '/api/resource/' ).success(function (data) {
                res(data);
            })

It says CORS error, CORS header 'Access-Control-Allow-Origin' missing. I think this not the error with the server CORS headers because when I change the grant url in the config or change the source course itself

return $http.post("" + config.baseUrl + "" + config.grantPath, data,    options).then(function(response) {
                            OAuthToken.token = response.data;
                            return response;
                        });

to the resource url, it works fine and I get the resource, the OAuth is working an there is no CORS request error

So my question is do I need to make any changes to make the resource urls to work?

I know this is out of the scpoe of this plugin but any help is appreciated. I have spent a lot of time on this and to no avail.

Improve the documentation to tell how to set token manually with OAuthToken

I wanted to set the token manually without having to use oauth API function but rather manually with OAuthToken service.
It took me quite some time, that it was so simple as

OAuthToken.token = data.token;

Where data.token is the token with token info coming from my api
In my case something like

token: {
 access_token:"YmJhODg5MGM3NDZlNTA4MjA4ZDU0NzViYTcxOGZjZGRmMGQ2NzE2ZDNjYTk5ODk0NDM4NzdjMzFjMjg1YzM0NQ",
expires_in: 3600,
refresh_token:"NWY1YjUyMzY3NTc0NjdiNTBlNDFkMGFkZWYxNjBlMjdjNzA5MDcxYzgwZjExNTc2Zjg0NzExNDE4YzU1Mzg2Nw",
scope: null,
token_type: "bearer"
}

I know it seem evident, but what's not written explicitly is not evident. So I suggest you add it in your doc.

Problems with Webpack

Hi Guys,

I'm trying to use angular-oauth2 with webpack, but I get this error

Chrome Inspector

Any idea?

I installed as you mention in the README file, but when I try to call it, seems like it try to read the local bower packages

require('angular');
require('angular-cookies');
require('query-string');
require('angular-oauth2');

even if i use

require('../../node_modules/angular-oauth2/dist/angular-oauth2.min.js');

Authorization header missing

Howdy seegno devers,

I have been trying to implement your library but cannot get it to perform the initial auth successfully. I am currently talking to a Java Spring-boot server running in a virtual box.

I can achieve the result using curl as per: -

curl -X POST -vu clientId:clientSecret http://192.168.56.2:8080/oauth/token -d 'username=username&password=password&grant_type=password'

{"access_token":"1b9186ae-cf63-454f-8424-12878cee7147","token_type":"bearer","refresh_token":"1fac8562-b6bf-4a06-bd39-6c439fd685ac","expires_in":35417,"scope":"read write"}

But when I run the ng implementation and looking in my browser debugger I see the lack of Authorization: Basic ... in the request and the response I get from the server is
Full authentication is required to access this resource

Relevant snippets of code below: -

app.config(['OAuthProvider', 'OAuthTokenProvider', function(OAuthProvider, OAuthTokenProvider) {
  OAuthProvider.configure({
      baseUrl: 'http://192.168.56.2:8080',
      clientId: 'clientId',
      clientSecret: 'clientSecret', // optional
      grantPath: '/oauth/token',
      revokePath: '/oauth/revoke'
  });

  OAuthTokenProvider.configure({
      name: 'token',
      options: {
          secure: false
      }
  });
}]);
var user = {username: 'username', password: 'password'}
OAuth.getAccessToken(user);

The data auth attributes end up being FORM data.

Is there something fundamental I am missing here. Your help would be appreciated, I am new to oAuth.

Regards
Peter

Moving to oauth organization

As part of a community effort to group oauth-related packages developed in js together, a new organization (oauthjs) has been created to host the most popular packages.

The idea behind this proposal is to increase package awareness and build even more community around them. The popular node-oauth-server will make the switch soon, as well as the koa wrapper koa-oauth-server.

In the next hours we will be moving this package to its new home too!

Change to new angular $cookies service

We should change to new $cookies released with angular 1.4.0-beta.6. Since we were using ipCookie only because it was possible to pass additional options so we could set important flags such as secure. It's important to note this is a breaking change, and will require to angular 1.4 and above, and since the current version is still beta, this will be released at the same time of angular 1.4 stable.

oauth:error event customization

oauth:error now is

{ status: 400, data: { error: 'invalid_grant' }

can i customize it?

i'm get error from my pytonhlib https://github.com/idan/oauthlib as:

{"error": "invalid_grant", "error_description": "Invalid credentials given."}

and http status code

Status Code:401 UNAUTHORIZED

Need some examples

I'm trying to use the OAuth.isAuthenticated(); method in a resolve function the $routeProvider.
The OAuth.getAccessToken(user, options) is working fine and I get the token back, saved in my cookies. But when I try to access /test route and want to check if user is authenticated I got:

 TypeError: Cannot read property 'token' of undefined
    at OAuth.isAuthenticated (angular-oauth2.js:91)

Here is my configuration

angular
  .module('myModule', [
    'ngRoute',
    'angular-oauth2'
  ])

  .config(['OAuthProvider', 'OAuthTokenProvider', function(OAuthProvider, OAuthTokenProvider) {
    OAuthProvider.configure({
      baseUrl: 'http://localhost:9000/',
      clientId: 'webapp',
      clientSecret: '6cb38775-8838-49a5-8a3a-b4400eebf3a9',
      grantPath: 'oauth/token',
      revokePath: 'oauth/revoke'
    });
    OAuthTokenProvider.configure({
      name: 'token',
      options: {
        secure: false
      }
    });
  }])

.config(['$routeProvider', 'OAuth', function ($routeProvider, OAuth) {
      .when('/test', {
        template: 'TEST',
        resolve: {
          auth: function ($q, $location) {
            var deferred = $q.defer();
            if ( ! OAuth.isAuthenticated() ) {
              deferred.reject();
              $location.path('/login');
            } else {
              deferred.resolve();
            }
            return deferred.promise;
          }
        },
      })

Any help would be super appreciated.

  • Damien

oauthInterceptor does not work for 401 (in my case)

When i log the rejection i get this result
image

The header from the API service is like this:
image

When i try the log the headers, they are null console.log(rejection.headers("www-authenticate"));

Am i doing something wrong or is the server response bad?

Unit test with OAuth

Hi,
i'm trying to test a controller which use OAuth.isAuthenticated() and OAuth.getAccessToken(),
but while trying to mock the OAuth module i'm getting the same error.

Error: `OAuthProvider` must be configured first.
    at new OAuth (http://localhost:8080/base/app/bower_components/angular-oauth2/dist/angular-oauth2.js:85:31)
    at OAuthProvider.$get (http://localhost:8080/base/app/bower_components/angular-oauth2/dist/angular-oauth2.js:173:20)
    at Object.invoke (http://localhost:8080/base/app/bower_components/angular/angular.js:4426:17)
    at http://localhost:8080/base/app/bower_components/angular/angular.js:4244:37
    at getService (http://localhost:8080/base/app/bower_components/angular/angular.js:4385:39)
    at Object.invoke (http://localhost:8080/base/app/bower_components/angular/angular.js:4417:13)
    at http://localhost:8080/base/app/bower_components/angular/angular.js:4248:71
    at forEach (http://localhost:8080/base/app/bower_components/angular/angular.js:336:20)
    at Object.createInjector [as injector] (http://localhost:8080/base/app/bower_components/angular/angular.js:4248:3)
    at Object.workFn (http://localhost:8080/base/app/bower_components/angular-mocks/angular-mocks.js:2409:52)

Here my test :

describe('MyCtrl', function() {
  var $scope;
  var OAuth;

  beforeEach(module('App.auth'));

  beforeEach(function() {

    var mockOAuth = {};
    inject(function($q) {
      /* angular-oauth2 OAuth mock */
      mockOAuth.accessToken = 'toto';
      mockOAuth.getAccessToken = function(credentials) {
        var self = this;
        var defer = $q.defer();
        defer.resolve(self.accessToken);
        return defer.promise;
      };

      mockOAuth.isAuthenticated = function() {
        return !!this.accessToken;
      };

      mockOAuth.setToken = function(token) {
        this.accessToken = token;
      };
    });

    module('App.auth', function($provide) {
      $provide.value('OAuth', mockOAuth);
    });

  });


  beforeEach(inject(function(_$controller_, _$rootScope_, _OAuth_) {

    $scope = _$rootScope_.$new();
    OAuth = _OAuth_;

    _$controller_('App.authController', {
      $scope:$scope,
      OAuth:OAuth
    });

    $scope.$digest();

  }));


  it('spec', function () {
  // Getting the error while no test specs. 
  });

And here is the controller

angular.module('App.auth')
  .controller('App.authController', [
        '$scope', '$http', '$route', '$location', '$localStorage', 'OAuth',
        function($scope, $http, $route, $location, $localStorage, OAuth) {

    $scope.login = function(credentials) {
      //on appelle l'url permettant de s'authentifier
      OAuth.getAccessToken(credentials)
        .then(function(/*token*/) {
         // ...
        });
    };


    if (OAuth.isAuthenticated()) {
      // ...
    } else {
      // ...
    }
  }]);


OAuthToken not being set after getAccessToken() success.

Hi, I'm doing OAuth.getAccessToken(credentials) and getting a successful hit on the server. The token is coming back fine, nothing wrong with request cycle. The issue happens when I call OAuth.isAuthenticated() after getAccessToken() runs, it always returns false. I stepped through the code and have a screenshot below. It looks like the OAuthToken.token is still undefined even after being set directly when the request comes back successful. I have the response.data on the right side and the breakpoint set right after the token should be set. Any help would be appreciated :)

Interceptor don't work

I add this library in my project

works fine but if a do a $http.get or $http.post my header don't contain any baerer token

can we help me?

Thanks

This is my request header ๐Ÿ‘
Accept
application/json, text/plain, /
Accept-Encoding
gzip, deflate
Accept-Language
it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Connection
keep-alive
Host
pagandoangular.local:8080
Referer
http://pagandoangular.local:8080/
User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

My config :
.config(['OAuthProvider', function(OAuthProvider){
OAuthProvider.configure({
baseUrl: 'http://cliente2.pagando.local:8080',
clientId: 'testclient',
grantPath: '/oauth',
revokePath: '/oauth',
clientSecret: 'testpass' // optional
});
}]);

invalid_grant and 401 UNAUTHORIZED

Hi, I'm using django-oauth-toolkit on the backend side.
It returns a 401 UNAUTHORIZED if the provided credentials are wrong:

{
    "error": "invalid_grant", 
    "error_description": "Invalid credentials given."
}

The interceptor assumes it's a 400 (https://github.com/seegno/angular-oauth2/blob/master/src/interceptors/oauth-interceptor.js#L21) and therefore it doesn't emit 'oauth:error'.
What do you think? Would it make sense to change that and allow 400 or 401 status codes instead only 400?

use guide

We have created a config . what's next?
Tell please. that needs to be done in the controller.

Basic Authentication doesn't work for refresh tokens

There are 2 ways to identify a client: Basic Authentication or with client_id and client_secret. See https://tools.ietf.org/html/rfc6749#section-2.3.1 and especially:

Including the client credentials in the request-body using the two
parameters is NOT RECOMMENDED and SHOULD be limited to clients unable
to directly utilize the HTTP Basic authentication scheme (or other
password-based HTTP authentication schemes). The parameters can only
be transmitted in the request-body and MUST NOT be included in the
request URI.

For requesting a token, this module supports adding the Basic Authorization header. Good.

However, for refreshing the token, one cannot customize the headers and thus it is impossible to use the recommended Basic Authorization header. Not good.
Additionally, the interceptor will send the old (invalid) token in that header.
So even if we would be able to set the Authorization header to (for example) Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW, the interceptor will overwrite it with the old token to (for example) Baerer tGzv3JOkF0XG5Qx2TlKWIA

So to fix this bug, we need to:

  1. Update the interceptor to not set the Authorization header for refresh token requests.
  2. Make sure the headers can be changed for refresh token

OAuthToken.removeToken() modifies config.options

I'm having trouble with OAuthToken.removeToken(), I debugged my application and found that ipCookies modifies config.options and so, in the next use of config.options it has 'exipires' set to an invalid date. Should it be passed a copy of config.options to ipCookie.remove()?
I vote for the ngCookies implementation that is waiting to be merged, will it be merged?
Thanks!

Authorization header is always sent

I have an issue concerning the interceptor, my problem is that it is adding the Authorization header to all requests including the getAccessToken & getRefreshToken, and this triggers a preflight request which is not supported from the server side.
I had to add the following code in the interceptor:

request: function(config) {
    // don't add the authorization header when the client is requesting a new token or refreshing one.
    if (angular.isDefined(config.data)) {
        var data = queryString.parse(config.data);
        if (angular.isDefined(data.grant_type) && (data.grant_type === 'password' || data.grant_type === 'refresh_token')) {
            return config;
        }
    }
    if (OAuthToken.getAuthorizationHeader()) {
        config.headers = config.headers || {};
        config.headers.Authorization = OAuthToken.getAuthorizationHeader();
    }
    return config;
}

Missing tag for version 2.1.1

Could you please create a tag for the new version 2.1.1 so we can get it with bower.
And also update the version number in bower.json

Handling 401 invalid_grant error

Using the FOSOAuthServerBundle, I ran into the situation when my OAuth2-enabled REST API returns a 401 invalid_grant error.
The oauthInterceptor implementation accepts only a 400 invalid_grant error and does not handle the 401 case. As a result, the oauth:error event is not triggered.
Is there a reason invalid_grant is handled only on a 400 response and not on the 401? Would it be ok to add this case in the interceptor as well ?

Thanks,
Mihai

Refresh token and http asynchronus queue

There is a bug when we use getrefreshtoken if the page has sent multiple asynchronus http requests. Because all the http requests 'refresh_token' are sent with the first access token ... The first request is ok : we get the new access token but the next requests in the queue use the old access token. So we get a 401 error ...

A little bit of concern.

Correct me if I am wrong, but this is a bad idea to store the clientId and secret on the client side:

OAuthProvider.configure({
      baseUrl: 'https://api.website.com',
      clientId: 'CLIENT_ID',
      clientSecret: 'CLIENT_SECRET',
    });

Add getToken() and setToken() methods instead of class getter/setter

I think we should remove getters/setters aproach and add methods to expose/manipulate token on OAuthToken service. I think it should be the class concern to have access to the property so that the property should be updated by the container object as a side-effect of other actions. Another point I noticed with #19, is that is quite complicated to override the getters and setters using a decorator for example. I should be as easy/quick as:

function oauthConfig($provide) {
  $provide.decorator('OAuthToken', function($delegate) {
    $delegate.prototype.getToken = function() {
      // your code here...
    };

    $delegate.prototype.setToken = function() {
      // your code here...
    };

    return $delegate;
  });
}

NOTE: This won't change the service usage, and can't be considered a breaking change since these are almost private methods.

Change payload type in getAccessToken() to JSON instead of query string

Hi, I'm wondering if there's any way to change the payload that the getAccessToken() request sends off to JSON instead of a query string? I can pass custom headers to the function to change it to Content-Type: application/json but I can't change the payload because it's doing a stringify and passing the data as a query string.

https://github.com/seegno/angular-oauth2/blob/04f0070ef28d2c7ac036627921bcfa3091a0daa8/src/providers/oauth-provider.js#L132

How to get the result from getAccessToken?

How to get the result from getAccessToken?
eg:

var result = OAuth.getAccessToken({username: $scope.data.email, password: $scope.data.password});

To get the return webservice messages...

Version depedency

"Include angular-oauth2 and dependencies. (angular, angular-cookies and query-string)"
What's the version of angular / angular-cookies ?

'angular' is undefined

I have downloaded angular-oauth2 and used the steps as mentioned in the documentation. When i run my application i get this error.

"Cannot read property 'module' of undefined " at this line
" var ngModule = angular.module("angular-oauth2", [ "ngCookies" ]).config(oau..."

basic auth for /oauth/token

Hi guys,
my /oauth/token is under basic auth. How use this library in this situation? I get this error
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

If I call wiht cUrl with curl -X POST -vu xxxxxxx:yyyyyyyy http://127.0.0.1:8383/oauth2/token ......

Error handling is not supported on getAccessToken

Upon $http.post in OAuthProvider::getAccessToken, error handling is not returned as a promise.
Adding this would allow login validation:

return $http.post("" + config.baseUrl + "" + config.grantPath, data, options).then(function(response) {
    OAuthToken.setToken(response.data);
    return response;
}, function (error) {
    return error;
});

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.