Git Product home page Git Product logo

node-oauth2-server's People

Contributors

anklos avatar artemabalmasov avatar chadkouse avatar chainlink avatar dependabot-preview[bot] avatar dependabot[bot] avatar fabianfett avatar jokesterfr avatar lfk avatar lucknerjb avatar markstos avatar maxtruxa avatar mjsalinger avatar nemtsov avatar nkzawa avatar nunofgs avatar omkarkhair avatar pritilender avatar razvanz avatar renovate-bot avatar robertjustjones avatar robinjmurphy avatar stanzhai avatar tbassetto avatar thomasdashney avatar thomseddon avatar towynlin avatar valera-rozuvan avatar visvk avatar wehriam 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

node-oauth2-server's Issues

How to disable OAuth 2.0 in a dev environment ?

Hi Thom,

I used node-oauth2-server v1.0 and I was able to disable OAuth 2.0 with a simple condition to set up a dev environment :

if (config.oauth.enabled) {
    app.use(oauth.handler());
    app.use(oauth.errorHandler());
    console.log ('Oauth 2.0 is enabled');
};

How could I recreate this behavior with node-oauth2-server v2.X ?

Cheers !
Alex

Allowed request randomly are prohibited

I use 'allow' option to pass certain urls without authentication:

var oauth = oauthserver({
    model: require('./src/oauth-model'),
    grants: ['password'],
    allow: ['/candidate/[0-9a-f]+/avatar', '/application/[0-9a-f]+/avatar'],
    debug: true,
    accessTokenLifetime: null,  // non-expiring tokens
    passthroughErrors: false
});

And on servers I randomly receive 400 error saying that access token has not been found.

It is same url, called continously. I tried even cURL to make sure browser is not an issue:

GET /application/528ca668e4b0f801e/avatar 200 30ms
GET /application/528ca668e4b0f801e/avatar 200 30ms
{ code: 400,
  error: 'invalid_request',
  error_description: 'The access token was not found',
  stack: undefined }
{ code: 400,
  error: 'invalid_request',
  error_description: 'The access token was not found',
  stack: undefined }
GET /application/528ca668e4b0f801e/avatar 400 1ms - 104b
GET /application/528ca668e4b0f801e/avatar 400 1ms - 104b
GET /application/528ca668e4b0f801e/avatar 200 32ms
GET /application/528ca668e4b0f801e/avatar 200 32ms
{ code: 400,
  error: 'invalid_request',
  error_description: 'The access token was not found',
  stack: undefined }
{ code: 400,
  error: 'invalid_request',
  error_description: 'The access token was not found',
  stack: undefined }
GET /application/528ca668e4b0f801e/avatar 400 1ms - 104b
GET /application/528ca668e4b0f801e/avatar 400 1ms - 104b
GET /application/528ca668e4b0f801e/avatar 200 26ms
GET /application/528ca668e4b0f801e/avatar 200 26ms

I use 1.5.3 version - can you give some clue what may be possibly wrong?

extendedGrant errors out after model.grantTypeAllowed is called

I have tried to follow the flow of the authentication process and it seems that once the "model.grantTypeAllowed" function is called, the OAuth server returns the following as a response:

$ http -f -v --auth test:test POST http://localhost:3000/oauth/token grant_type=client_credentials
POST /oauth/token HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, compress
Authorization: Basic dGVzdDp0ZXN0
Content-Length: 29
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:3000
User-Agent: HTTPie/0.6.0

grant_type=client_credentials

HTTP/1.1 400 Bad Request
Connection: keep-alive
Content-Length: 123
Content-Type: application/json; charset=utf-8
Date: Tue, 18 Feb 2014 09:43:32 GMT
X-Powered-By: Express

{
    "code": 400, 
    "error": "invalid_request", 
    "error_description": "Invalid grant_type parameter or parameter missing"
}

This is the code for the model.grantTypeAllowed:

var authorizedClientIds = ['test', 'def2'];
model.grantTypeAllowed = function (clientId, grantType, callback) {
  console.log(5);
  if (grantType === 'password' || grantType === 'client_credentials') {
    return callback(false, authorizedClientIds.indexOf(clientId.toLowerCase()) >= 0);
  }

  callback(false, true);
};

The code in the grantTypeAllowed function is straight from the example and is setup the way it is now for testing purposes. Just an FYI.

And here is the code for the oauth server:

app.configure(function() {
  app.oauth = oauthserver({
    model: require('./model'),
    grants: ['client_credentials'],
    debug: true
  });
  app.use(express.bodyParser()); // REQUIRED
});

app.all('/oauth/token', app.oauth.grant());

Any ideas on why oauth would return that json response?

Trouble migrating from 1.5 to 2.0

I have created a couple of custom middlewares, one is enriching request with data about currently logged in user. Order in main .js script is as follows:

var app = express();

// ...
//Create OAuth2
var oauth = oauthserver({...});

// ...
app.use(express.bodyParser());
app.use(express.methodOverride());

// ... enable OAuth
app.all('/oauth/token', oauth.grant());
// ...
app.use(require('./src/middleware/userinfo').userInfo);
app.use(require('./src/middleware/tracking'));
// ...
app.use(app.router);
// ... routes go here
require('./src/routes/ping')(app);

Now app is able to obtain access token, but it fails on any requests because none of my middlewares were executed (I added log statements to check this).

If I move app.all('/oauth/token', oauth.grant()); below middlewares are defined, I get HTTP 400 - access token is invalid.

I see configuration changed a little in 2.x and I would appreciate any hint.

What is the role of redirect_uri in implementation of refresh_token oauth

i read the provided documentation for node-oauth2-server.i am trying to run this example.i set up all the things:

var express = require('express');
oauthserver = require('node-oauth2-server');

var app = express();
app.configure(function() {
var oauth = oauthserver({
model: require('./model'), // See below for specification
grants: ['refresh_token'],
allow:['/path1'],
debug: true
});
app.use(express.bodyParser()); // REQUIRED
app.use(oauth.handler());
app.use(oauth.errorHandler());
});

app.listen(3000);

Now i get the concept of model object for password.for getting refresh_token what to do ?? for example in google oauth.first we get code parameter on redirect uri then we make a call to token url.how to implement refresh_token oauth.and no role is mentioned of redirect_uri. but its required for 3 legged oauth.Please explain implementation. on which url user have to direct for login.

Any ETA on version 3.0?

We're considering a deployment in a couple of weeks and wondered if we should be waiting. Is it going to be painful to migrate to 3.0?

Invalid arguments in model.js (MongoDB example)

at line 90 and 115 in examples / mongodb / model.js
now: function (token, clientId, userId, expires, callback)
must be: function (token, clientId, expires, userId, callback)
And also inside methods userId is not ID, it's user object.
So maybe change in arguments userId to user.

Alternative Node package comparison

Anyone any opinion on node-oauth2-server Vs oauth2orize for implementing a Node Oauth2 Identity provider?

I'm after a full provider IE something that provides a method to do full user account management..

Thanks :)

using method DELETE and oauth error

hi

i was trying to use DELETE method on my api project but you oauth module blocked the request by this error : When putting the token in the body, the method must be POST.

Examples

Would make it a lot easier to approach

null clientSecret question

Hello,

Im a little new with OAuth2. Im not 100% clear on how to pass in a null clientSecret.

I noticed under getClient (clientId, clientSecret, callback) i can pass in string|null for clientSecret

However, i keep seeing this error "Missing client_secret parameter" when i try posting with this body
"grant_type=password&username=johndoe&password=A3ddj3w&client_id=spa"

I noticed this is from this line master/lib/grant.js:88

Im not sure exactly how to pass in a null client_secret. Can you kindly assist?

When error occurs, return `message` and `developerMessage` instead of `errorDescription`.

There are various beliefs on how to design APIs and how to handle errors. Some of the best advices that I know are given by Les Hazlewood in REST+JSON API Design - Best Practices for Developers [Youtube] where he suggests to output the response consistently with the following properties:

  1. status: a numeric value of the HTTP status code which should be returned in every response.
  2. error: an ASCII error code if any.
  3. message: an end-user friendly message which should be displayed to a user directly.
  4. developerMessage: a more technical error message designed for application developers.

As of [email protected], the following error is returned when access token is missing.

{
  "code": 400,
  "error": "invalid_request",
  "error_description": "The access token was not found"
}

Considering the above suggestions, here is how it would look when an error occurred.

{
  "status": 400,
  "error": "invalid_request",
  "message": "The application you are trying to use seems to be configured incorrectly. Please contact the application developers.",
  "developerMessage": "The access token was not found."
}

It would be awesome if you considered this change. If necessary, I can send a PR.

Throw 401 when trying to access a protected resource.

Hey,

I know it's not the place, but first, thanks,
Although the key feature of oauth is the authorization grant, I still chose to use this module because it's the first cleanest and well tested oauth server for node ๐Ÿ‘

Back to the reason I opened an issue: authorise.js produces an invalid_request for a missing token and invalid_grant when a token is invalid,

I think this should be improved a bit in a way where:

missing token should cause 'missing_token', and invalid token should cause 'invalid_token', both cases, when accessing a protected resource should respond with error 401, otherwise it's really hard to determine in the client side whether the request was malformed or just a valid call of unauthorized request.

Thanks

any way for Custom Error Messsage

i have two doubt

  1. i got the point of implementing all the functions but where function getAccessToken and getRefreshToken utilized or called ?? i get the point from your comment How to implement.
    2.when ever i pass an error in any function like

model.saveAccessToken = function (accessToken, clientId, userId, expires, callback) {

callback({'error':'invalid response'},false);

};

then it will give the response
{
code: 503
error: "server_error"
error_description: "server_error"
}
if there is any custom mistake or error then can i change this response to some thing else manually .can i customize error message using this library??

how to issue refresh token?

how the refresh token can be created?

or what is the url to issue refresh token?

or anything about it ... plz help

Be more lax about data stored in access token

Currently, lib/grant.useAuthCodeGrant enforces a constraint on "user" data that it has an id parameter. Why? It seems unseemly to even pass around an object called user. I'd rather that I could just attach any data I want to the access token.

As I understand it, the purpose of the user object is to be put onto an incoming HTTP request by lib/authorise.checkToken (i.e. using authorise as middleware in a route). I would rather that this be a fallback behavior, and that I could, instead, explicitly define what data gets populated on my request object (as part of the model).

Let me know how you feel about this. I will be happy to send a pull request, if desired.

test.js in root folder not work

in empty folder project
$ npm install

[email protected] node_modules/supertest
โ”œโ”€โ”€ [email protected]
โ””โ”€โ”€ [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

[email protected] node_modules/mocha
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ””โ”€โ”€ [email protected] ([email protected])

[email protected] node_modules/express
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”€ [email protected] ([email protected])
โ””โ”€โ”€ [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected])


$ node test.js

Error: .post() requires callback functions but got a [object Undefined]

grant.js useRefreshTokenGrant

grant.js line 249

refreshToken.clientId does not exist. we correct in refreshToken.client_id or we miss someting?

thank you

if (!refreshToken || refreshToken.client_id !== self.client.clientId) {         
  return done(error('invalid_grant', 'Invalid refresh token'));
} else if (refreshToken.expires !== null &&
    refreshToken.expires < self.now) {
  return done(error('invalid_grant', 'Refresh token has expired'));
}

if (!refreshToken.user_id) {
  return done(error('server_error', false,
    'No user/userId parameter returned from getRefreshToken'));
}

self.user = refreshToken.user_id || { id: refreshToken.userId };

if (self.model.revokeRefreshToken) {
  return self.model.revokeRefreshToken(token, function (err) {
    if (err) return done(error('server_error', false, err));
    done();
  });
}

done();

});
}

What is "client"?

On getClient() one is expected to return a "client" but the README doesn't talk about it.
What should a client have?

500 Internal Server Error

I am receiving a 500 Internal Server Error every time authentication fails. With in the body of the response an uncorrectly formatted json. The keys should have single quotes around them and the status in the header should be set correctly.

{
  code: 400,
  error: 'invalid_grant',
  error_description: 'User credentials are invalid',
  stack: undefined
}

I am not exactly sure why, but I think it has something to do with how the error is thrown. For instance in usePasswordGrant() the done function is called with the error object. This also throws a Server Error in my case even though it's not really a server error.

A nice solution for me was to send this object to the client. In the runner.js file I changed line 16 from:
if (err || pos === last) return next(err);
to:

if (err) {
  if (err.headers) context.res.set(err.headers);
  return context.res.json(err.code, err);
}
if (pos === last) return next();

This way the error gets send back to the client like it should (in my opinion). The changes I made are in my fork.

Thoughts?

Question: Login example in PostgreSQL mockup

// Handle login
app.post('/login', function (req, res, next) {
  // Insert your own login mechanism
  if (req.body.email !== '[email protected]') {
    res.render('login', {
      redirect: req.body.redirect,
      client_id: req.body.client_id,
      redirect_uri: req.body.redirect_uri
    });
  } else {
    // Successful logins should send the user back to the /oauth/authorise
    // with the client_id and redirect_uri (you could store these in the session)
    return res.redirect((req.body.redirect || '/home') + '?client_id=' +
       req.body.client_id + '&redirect_uri=' + req.body.redirect_uri);
  }
});

I am going rounds with oauth on an API i am trying to get right, I am having trouble with this one particular example ^^ in: https://github.com/thomseddon/node-oauth2-server/blob/master/examples/postgresql/index.js

I hate to ask for a gimme, but is this where I can plant a local username-password strategy? If I am trying to store a session with a bearer token, where do I plant this with X, (passport or something)? I have something like:

// model for oauth
model.getUser = function (username, password, callback) {
  Models.User.find({
    where: ['lower("Users"."username")=? AND "Users"."deletedAt" IS NULL', username.toLowerCase()]
  }).success(function(user) {
    if (!user) { 
      return callback('Unknown user ' + username ); 
    }
    user.verifyPassword(password, function(result) {
      if (result)
        return callback(null, user);
      else
        return callback('Invalid password');
    });
  })
};

//passport local stategy
passport.use(new LocalStrategy(
  function(username, password, done) {
    process.nextTick(function () {
      Recommender.Models.User.find({
        where: ['lower("Users"."username")=? AND "Users"."deletedAt" IS NULL', username.toLowerCase()]
      }).success(function(user) {
        if (!user) { 
          return done(null, false, { message: 'Unknown user ' + username }); 
        }
        user.verifyPassword(password, function(result) {
          if (result)
            return done(null, user);
          else
            return done(null, false, { message: 'Invalid password' });
        });
      })
    });
  }
));

to verify a user. Can you organize my thoughts on what i should be doing on the app.post('/login') route? Maybe I am way off... Thanks for making good code available to guys trying to do side projects with full time jobs!

2.x MongoDB example is wrong

I get an error when making a refresh_token request on a Mongoose-based setup. The error I get states that the client_id is invalid, and when debugging I noticed that on

function useRefreshTokenGrant (done) {
  var token = this.req.body.refresh_token;
  if (!token) {
    return done(error('invalid_request', 'No "refresh_token" parameter'));
  }

  var self = this;
  this.model.getRefreshToken(token, function (err, refreshToken) {
    if (err) return done(error('server_error', false, err));

    if (!refreshToken || refreshToken.clientId !== self.client.clientId) {
      return done(error('invalid_grant', 'Invalid refresh token'));
    } else if (refreshToken.expires !== null &&
        refreshToken.expires < self.now) {
      return done(error('invalid_grant', 'Refresh token has expired'));
    }

    if (!refreshToken.user && !refreshToken.userId) {
      return done(error('server_error', false,
        'No user/userId parameter returned from getRefreshToken'));
    }

    self.user = refreshToken.user || { id: refreshToken.userId };

    if (self.model.revokeRefreshToken) {
      return self.model.revokeRefreshToken(token, function (err) {
        if (err) return done(error('server_error', false, err));
        done();
      });
    }

    done();
  });
}

at if (!refreshToken || refreshToken.clientId !== self.client.clientId) {}, the refreshToken has no clientId, but just the'client_id. I'm not very familiar with the codebase, but I know that somewhere there's an internal function that converts a model object from client_id to clientId, so there might be a leak where this conversion isn't taking place.

After manually fixing it, I notice that the next error I get is the one below, but if I figure out what's causing it I'll submit a PR or an issue.:

{
  "code": 503,
  "error": "server_error",
  "error_description": "server_error"
}

Add support for MAC tokens

While the current randomly generated tokens can't easily be guessed, it'd be great to add a MAC support for generated tokens. For reference, this ruby implementation handles authorization tokens with HMAC.

Edit: The original description mentioned UUID, but that was a mistake as the current implementation does not use UUIDs and rather uses a hash of random bytes (see comments below for details).

ignore paths

hi

how can i make the oauth server ignoring some paths while checking for access token

for example :

http://localhost:1337/allowed

dont use oauth authorization when the get uri is 'allowed'
?

UserId is lost on a 2nd refresh token

Hi Thom,

I'm having an issue with refresh_token. Here is how I get it :

  • A user is logged in, he receives an access token and a refresh token
  • User sends authentified requests using access token, until...
  • The access token has expired, the refresh token is used to give another access token and refresh token to the user.
  • User sends authentified requests using access token, until...
  • The access token has expired, the refresh token is used to give another access token and refresh token to the user, but this time there is no UserId given to saveAccessToken and saveRefreshToken, I save tokens in mongodb anyway.
  • User sends authentified requests using access token, until...
  • In getRefreshToken, error No user/userId parameter returned from getRefreshToken occurs, and the user is disconnected

Is it a normal behavior? Am I missing something?

Bye,
Alex

How to verify token and authorise routes are working?

I'm trying to see if i got the postgres example working.

Verify user creation

(based on the tests)

$ curl http://127.0.0.1:3000/oauth/token --request POST --data  '{"grant_type": "password", "client_id": "thom", "client_secret": "nightworld", "username": "thomseddon", "password": "nightworld"}' --header "Content-Type: application/x-www-form-urlencoded"
#{
# "code": 400,
# "error": "invalid_request",
# "error_description": "Invalid or missing grant_type parameter"
#}

Verify user authorization

(based on the tests)

$ curl http://127.0.0.1:3000/oauth/authorise --request POST --data  "{response_type: 'code', client_id: 'thom', redirect_uri: 'http://nightworld.com'}" --header "Content-Type: application/x-www-form-urlencoded"
# TypeError: Cannot read property 'user' of undefined
# ln:20  if (!req.session.user) {

Account management

Is there any examples of extending this server to include:

  • User account creation
  • Admin User account management
  • Password reset functionality

Or is it expected the admin will implement these things themselves?

SAML 2.0 Bearer Assertion for OAuth 2.0

First let me just say great work on this. I've been following this project for a while and I'm really happy how it's coming out. There are zero Node OAuth2 implementations up to date and you are solving that problem. Awesome.

There is a SAML 2.0 Bearer Assertion type out which is really quite useful. I know that nobody likes depending on a PHP/Ruby lib just to implement SAML support if they are writing a Node app, so I can definitely see this as something being used.

The official specification is here:
http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-17

RC1

I've released the 2.0 branch as RC1 as it's been pretty stable for a few months.

I'm hoping to make the switch to defaulting to 2.0 within a week or so :)

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.