EzDevInfo.com

oauth2orize

OAuth 2.0 authorization server toolkit for Node.js.

Why loopback-component-oauth2 include oauth2orize's source code totally?

I am testing loopback component to use it to make my product. Currently, loopback-component-oauth2 has oauth2orize source code in its source directory. As you know, oauth2orize is a node library that implements details of oauth2 protocol. I think that it's enough for loopback-component-oauth2 just to do require('oauth2orize') to use oauth2orize library. Is there any specific reason to including oauth2orize source code into 'loopback-component-oauth2'?

Thanks in advance.


Source: (StackOverflow)

Node.js oAuth2 implementation - advice on strategy and flow - Passport and Oauth2orize

I am currently developing a REST API and associated web based responsive app. My requirements are as follows:

  • REST API must be secured using authentication, and be developer friendly
  • Web application should support sessions as well as be able to access the REST endpoints
  • Later, I would like to allow other apps to be developed against my API.
  • Later, I would also want users to login to the app using remote oAuth2 providers e.g. Twitter

So I implemented an oAuth2 workflow using a resource Owner Password Flow. This has the following workflow:

  • http POST /oauth/token grant_type=password client_id=mobileV1 client_secret=abc123456 username=andrey password=simplepassword

  • http /api/userinfo Authorization:'Bearer TOKEN'

The above uses a combination of Passports BasicStrategy (to secure /oauth/token), ClientPasswordStrategy (authenticates clients using a client ID/secret) and BearerStrategy (use token against API).

I am now at a stage where I need to implement the site login strategy i.e. sessions however that suggest using Passports LocalStrategy.

Should I replace my current BasicStrategy implementation for LocalStrategy? The BasicStrategy was implemented to restrict access to the /oauth/token resource, however does not start a session. My understanding is that the BasicStrategy is to be used with API endpoints where the architecture is stateless. As a result, sessions are not required but can be used.

Questions:

1) Is the oAuth2 using a resource Owner Password Flow suitable for these purposes?

2) Should I replace my current BasicStrategy implementation for LocalStrategy or add sessions to the BasicStrategy?

Appreciate any comments.


Source: (StackOverflow)

Advertisements

oauth2orize sample returns AuthorizationError: not authorized

I've downloaded the oauth2orize provider code example and the sample oauth client suggested in the docs and I'm getting the following error:

500 AuthorizationError: not authorized at validated (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/middleware/authorization.js:131:36) at /Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/oauth2.js:180:14 at Object.exports.findByClientId (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/db/clients.js:24:10) at exports.authorization.res.render.transactionID (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/oauth2.js:174:16) at /Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/middleware/authorization.js:167:9 at pass (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/server.js:262:26) at pass (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/server.js:280:9) at pass (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/server.js:271:11) at Server._parse (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/server.js:285:5) at authorization (/Users/trevorallred/projects/pics/node-soa/oauth2orize/examples/all-grants/node_modules/oauth2orize/lib/middleware/authorization.js:118:12)

I'm running the client here: http://localhost:3002/ I click the link to "Connect with example-oauth2orize"

It redirects me to the provider: http://localhost:3000/login

After logging in with "bob" I'm sent to this error page.

The only modifications I've made are to oauth-config.js in the example client.

'use strict';

module.exports = {
        provider: {
                protocol: "http",
                host: "localhost:3000",
                profileUrl: "/api/userinfo"
        },
        consumer: {
                protocol: "http",
                host: "localhost:3002"
        }
};

I tried modifying oauth-consumer-config.js after I saw this bug report but it didn't seem to change any behavior.

module.exports = {
  name: 'Example Consumer App'
, icon: 'http://example.com/icon_64.png'
, clientId: 'trevorclient'
, clientSecret: 'kasdfasdfoq34t134tg109gqerg1gjc'
};

Source: (StackOverflow)

oauth2orize redirect_uri issue

I'm attempting to customize the oauth2orize all-grants example for my use. I can run the all-grants as-is and everything works (as you would expect), but when I run my customized version, I always end up with this error:

Error: Unable to issue redirect for OAuth 2.0 transaction
at Object.response [as handle] (C:\Dev\Expy\api\node_modules\oauth2orize\lib\grant\code.js:122:41)

I've been digging into this a bit and it seems there is a property of the txn variable within that function that should be named redirectURI and should be populated with the redirect_uri from the query string of the initial request to the /dialog/authorize page. For some reason this doesn't happen on my example app. Is this caused by an express version difference? That is the biggest difference that I see between the example code and my customizations. The all-grants uses express 2.* and my app will use express 4.*.

If it isn't an express version issue, where should I start looking in my code for the issue?

For reference, this is what I see in my app for the txn object:

txn: {
    "transactionID": "evlUd2q4",
    "client": { ... },
    "req": {
        "type": "code",
        "clientID": "5C3B4438-433F-11E5-A532-74653C701F13"
    },
    "user": { ... },
    "res": {
        "allow": true
    }
}

and this is what I see in that same object with the example (note the presence of the redirectURI in req and in the txn itself):

txn: {
    "transactionID": "EEcYp3Uj",
    "client": { ... },
    "redirectURI": "http://localhost:3000/api/userinfo",
    "req": {
        "type": "code",
        "clientID": "abc123",
        "redirectURI": "http://localhost:3000/api/userinfo"
    },
    "user": { ... },
    "res": {
        "allow": true
    }
}

Source: (StackOverflow)

Confusion around oauth2 and where access_token and refresh_token should be stored

Would be great to get some deeper understanding of how to secure this setup:

  • Node.js / ExpressJS / Oauth2orize REST API that is protected with oauth2, and hosted on api.domain.com

  • Backbone.js application that is hosted on domain.com served via a Node.js / ExpressJS Server

Currently the following happens:

1 - User visits application in browser, provides username and password, these are posted to the wrapper (domain.com/login)

2 - The wrapper augments the username and password with a client_id and client_secret and passes these along with username and password through to api.domain.com/oauth/token. This is done rather than just dealing direct with api in the javascript application in order to keep client_id and client_secret secure. This process is only intended for authing, once a token exists the plan is for the JS client to communicate directly with the api.

3 - api.domain.com/oauth/token checks user and password credentials and issues a refresh_token and access_token if credentials pass, alternatively a 401 is returned

4 - token response including both refresh_token and access_token is returned to the javascript application as the response to the domain.com/login request. Currently the JavaScript client handles setting Authorization headers and obtaining new access_tokens using the refresh_token.

I have a number of questions:

Firstly I'm confused in regard to access_token and refresh_token, I suspect I should not be passing refresh_token to the browser at all - should it be instead be cached on the proxy with refresh performed via the proxy? Or is it fine for the refresh_token to be passed to the Javascript App?

Is it fine for either the access_token or refresh_token be cached in the browser? Eg cookies or localstorage. If so, how is this secure? And if not, wouldn't the user have to reauthenticate any time they refreshed the browser?

If someone could illustrate the 'right' steps to take in terms of handling the refresh_token and access_token in the wrapper server and the JavaScript application, that would be much appreciated.


Source: (StackOverflow)

Secure nodejs app with OAuth2, not automatically redirected to allow / deny page

I've set up a project to secure a sails application with OAuth2: https://github.com/lucj/sails-oauth2-api

I have a problem with the Authorization Code Grant that I do not manage to solve.

Basically, This are the steps I follow:
- run the sails app
- run the unTrustedClient (node untrustedClient.js within the example folder)
- from a web browser, I then issue the following URL:

http://localhost:1337/oauth/authorize?client_id=O3UTGRFNI1&response_type=code&redirect_uri=http://localhost:1339&scope=http://localhost:1337

Note: the value of the client_id is the one displayed for untrustedTestClient in the sails terminal when the application starts

This redirect me toward the 'login' page, which is fine.

https://dl.dropboxusercontent.com/u/2330187/login.png

But when I submit the credentials (me@gmail.com /password by default) I'm redirected towards /index and not toward the original URL (the one above).

https://dl.dropboxusercontent.com/u/2330187/index.png

I need to re-issue the URL above for the dialog page (the one with the Allow / Deny options) to be displayed.

https://dl.dropboxusercontent.com/u/2330187/allow_deny.png

I'm using 'connect-ensure-login' middleware.

app.get('/oauth/authorize',
    login.ensureLoggedIn(),
    server.authorize(function(clientId, redirectURI, done) {

      Client.findOne({clientId: clientId}, function(err, client) {
        if (err) { return done(err); }
        if (!client) { return done(null, false); }
        if (client.redirectURI != redirectURI) { return done(null, false); }
        return done(null, client, client.redirectURI);
      });
    }),
    server.errorHandler(),
    function(req, res) {
      res.render('dialog', { transactionID: req.oauth2.transactionID,
                             user: req.user,
                             client: req.oauth2.client
      });
    }
  ); 

How can I fix this so the redirection is done automatically once I enter the credentials ?


Source: (StackOverflow)

client_id undefinded on grant_type=password (oauth2orize)

I am creating an API in nodejs with oauth2orize and passport, but when I ask for the token, the client_id parameter is undefined.

Oauth2orize:

server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, callback) {
    console.log(client);    // This is undefined

Post:

grant_type: password,
client: id_client,    // I tried with client_id, clientId, id...
username: username,
password: password

Why is the client parameter is undefined?

Thanks a lot


Source: (StackOverflow)

Angular + Node + Express + Passport + oauth2orize unique CORS issues

I've built an API to use for local auth and Facebook auth.

I'm using node, express, passport and oauth2orize for the authorization process.

I'm now running the API perfectly through terminal applications and API testing suites, however, when making calls to my authentication endpoints from angular I receive the following:

Local auth:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

http://localhost:4200/oauth2/auth
    ?client_id=[CLIENT_ID]
    &redirect_uri=http:%2F%2Flocalhost:4200%2Foauth2%2Fauth%2Fcallback (http://localhost:4200/oauth2/auth/callback)
    &response_type=code.

This can be fixed by moving the resource to the same domain or enabling CORS.

Facebook auth:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

https://www.facebook.com/dialog/oauth
    ?response_type=code
    &redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fauth%2Ffacebook%2Fcallback (http://localhost/auth/facebook/callback)
    &client_id=[CLIENT_ID].

This can be fixed by moving the resource to the same domain or enabling CORS.

I have had CORS issues in the past and integrated the npm 'cors' middleware module found at https://www.npmjs.com/package/cors

CORS init:

var cors = require('cors');
api.use(cors());

With my previous issues, this was sufficient, however, with these new CORS issues it's not helping.

I've also noticed, in Firefox, if I click on the error message, a new dialog window opens up as it should and the server continues to correctly authorize the user.

Could anyone help?

UPDATE 1:

Check comments for screenshot of debug info.

UPDATE 2:

Response headers for the last 2 requests performed in the login flow.

  1. 204:

    Access-Control-Allow-Credentials: true
    Connection: keep-alive
    Date: Fri, 06 Feb 2015 15:26:43 GMT
    Vary: Origin
    X-Powered-By: Express
    access-control-allow-headers: authorization
    access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
    access-control-allow-origin: http://localhost:8100
    
  2. 302:

    Access-Control-Allow-Credentials: true
    Connection: keep-alive
    Content-Length: 138
    Content-Type: text/plain; charset=utf-8
    Date: Fri, 06 Feb 2015 15:26:43 GMT
    Location: http://localhost:4200/oauth2/auth/callback?code=[CODE_HERE]
    Set-Cookie: connect.sid=[SID_HERE]; Path=/; HttpOnly
    Vary: Origin, Accept
    X-Powered-By: Express
    access-control-allow-origin: http://localhost:8100
    

Source: (StackOverflow)

How to return to OAuth2 consumer's redirect url with error message in OAuth2orize?

Generally, with the Authorization Code grant type, OAuth2 provider redirects user agent with the authorization code code as the parameter in the redirect url. (E.g. http://consumer.oauth2.com/oauth2/callback?code=abc)

I am using OAuth2orize as a OAuth2 provider, it would help me to return the authorization code to the redirect url if the authentication succeeded.

But while it is failed, I can only respond with the error message directly to the POST login endpoint, which will just display the message in a blank HTML page.

Instead, I want to return the error message with the redirect url. In other words, no matter the authentication succeed or not, I would always redirect the user agent to the redirect url, but it would contains parameters code if successful authentication or error if fail authentication.

(E.g. http://consumer.oauth2.com/oauth2/callback?error=Incorrect%20username%20or%20password)


Source: (StackOverflow)

OAuth 2.0 authentication for own mobile client

I am developing an app using node.js which will also have an mobile client. I am looking to make the authentication using OAuth 2.0. Is there any good module which allows me to have OAuth 2.0 authentication server?

I looked at a subsidiary module of Passport "OAuth2orize". I found it quite good enough, but the real problem was understanding how it will work for my own app (the example and docs specify about third party authorisation).

Basically what I want is that the client logs in with client id, user's username, user's password and there by I hand him a token after verifying the above 3 things. But the problem with Oauth2orize is that there there are redirect URI and all which is confusing me a lot.

Please help me know as to how can i achieve this using Oauth2rize or any other really good module. Or If its easy enough I can also roll my own, but will that be a good idea regarding security ??


Source: (StackOverflow)

Protecting an API with Scopes (oauth2orize, passport, express, Nodejs)

I'm trying to create an API with node/express, and secure it with Passport and oauth2orize. I've got the API working, I've got the oauth2 stuff working, but I can't seem to figure out how to implement securing API methods with scopes.

The oauth2orize token hander-outer:

server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
scope = scope || ['unauthorized'];
db.collection('oauth_users').findOne({username: username}, function (err, user) {
    if (err) return done(err);
    if (!user) return done(null, false);
    for (i in scope)
        if(user.scope.indexOf(scope[i]) < 0) return done(null, false);
    bcrypt.compare(password, user.password, function (err, res) {
        if (!res) return done(null, false);

        var token = utils.uid(256)
        var refreshToken = utils.uid(256)
        var tokenHash = crypto.createHash('sha1').update(token).digest('hex')
        var refreshTokenHash = crypto.createHash('sha1').update(refreshToken).digest('hex')

        var expirationDate = new Date(new Date().getTime() + (3600 * 1000))

        db.collection('oauth_access_tokens').save({token: tokenHash, expirationDate: expirationDate, clientId: client.clientId, userId: username, scope: scope}, function (err) {
            if (err) return done(err)
            db.collection('oauth_refresh_tokens').save({refreshToken: refreshTokenHash, clientId: client.clientId, userId: username}, function (err) {
                if (err) return done(err)
                done(null, token, refreshToken, {expires_in: expirationDate})
            })
        })
    })
}) }))

The passport bearer token checker:

passport.use("accessToken", new BearerStrategy(
{passReqToCallback: true},
function (req, accessToken, done) {
    console.dir(req.params);
    var accessTokenHash = crypto.createHash('sha1').update(accessToken).digest('hex')
    db.collection('oauth_access_tokens').findOne({token: accessTokenHash}, function (err, token) {
        if (err) return done(err);
        if (!token) return done(null, false);
        if (new Date() > token.expirationDate) {
            db.collection('oauth_access_tokens').remove({token: accessTokenHash}, function (err) { done(err) });
        } else {
            db.collection('oauth_users').findOne({username: token.userId}, function (err, user) {
                if (err) return done(err);
                if (!user) return done(null, false);
                // no use of scopes for no
                var info = { scope: '*' }
                done(null, user, info);
            })
        }
    })
}))

The API security:

router.get('/restricted', passport.authenticate('accessToken', { scope: "unauthorized", session: false }), function (req, res) {
res.send("Restricted Function");})

I can find no example of accessing the "scope" option passed in passport.authenticate to passport.use. I was thinking it was in the req object, but I can't find it in there. Any help?


Source: (StackOverflow)

How to implement oauth2orize new exchange police for mobile number and security pin

How to implement custom exchange police

I want to generate token for mobile number and security pin like client password strategies


Source: (StackOverflow)

OAuth2orize login flow looping infinitely

Looking to get an OAuth2 endpoint set up for my website. I am using OAuth2orize on the OAuth server, and passport-oauth on the client server.

I'm using the oauth2orize example almost verbatim to get it working first.

When I begin the login flow, it sends me to the login page (good so far), I log in and it sends me to the dialog (also good), and then when I click allow, it just loops me back to the same page over and over again (the allow/deny dialog).

Anybody have any idea what I'm doing wrong? I know it's actually sending me back to my app (with code, that my app should exchange for a token), but it seems to just bounce me right back to the dialog:


Source: (StackOverflow)

Securing a nodejs / sailsjs API with OAuth2

I have developed a REST API with sailsjs and I'd like to add OAuth2 authorization to secure this API. I'm quite new to OAuth and I'm not sure where to start.

I found several modules that could be used for this purposes, for instance oauth2orize and an example of its usage https://github.com/aaron524/sails-oauth2-provider-example but I do not fully understand how this is working internally.

Basically, I'll have several clients consuming the API I'm developing: - clients that I trust and that I'd like to use with the "Resource Owner Credential Authorization" - clients that I do not trust and that will connect using the Authorization Code flow

I was thinking of adding a trusted property to the Client model within the sails application and then when a user will log onto an application: - he will have a direct access to its resources (case of the trusted application) - he will be requested to approve or deny the application from accessing his resources (case of the untrusted application)

Is this a good approach ? Any pointers on how to select the corresponding strategy based on the client trusted level ?

UPDATE

I've setup the following project on GitHub, using several tutorial and projects I found.

https://github.com/lucj/sails-oauth2-api  

This project is not functional yet.

I'm still not clear on how to select the correct grant type (authorization code vs resource owner's password) when the user consume the API through an application. How to integrate this check in the policies ?

I do not manage to create the link between the OAuth endPoint (/oauth/authorize, /oauth/token) and the call to oauth2orize. Any idea ?


Source: (StackOverflow)