Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

OAuth 2.0 authorization server toolkit for Node.js.

License

NotificationsYou must be signed in to change notification settings

jaredhanson/oauth2orize

Repository files navigation

OAuth2orize is an authorization server toolkit for Node.js. It provides a suiteof middleware that, combined withPassportauthentication strategies and application-specific route handlers, can be usedto assemble a server that implements theOAuth 2.0protocol.


Advertisement
Node.js API Masterclass With Express & MongoDB
Create a real world backend for a bootcamp directory app


Status:BuildCoverageDependencies

Install

$ npm install oauth2orize

Usage

OAuth 2.0 defines an authorization framework, allowing an extensible set ofauthorization grants to be exchanged for access tokens. Implementations arefree to choose what grant types to support, by using bundled middleware tosupport common types or plugins to support extension types.

Create an OAuth Server

CallcreateServer() to create a new OAuth 2.0 server. This instance exposesmiddleware that will be mounted in routes, as well as configuration options.

varserver=oauth2orize.createServer();

Register Grants

A client must obtain permission from a user before it is issued an access token.This permission is known as a grant, the most common type of which is anauthorization code.

server.grant(oauth2orize.grant.code(function(client,redirectURI,user,ares,done){varcode=utils.uid(16);varac=newAuthorizationCode(code,client.id,redirectURI,user.id,ares.scope);ac.save(function(err){if(err){returndone(err);}returndone(null,code);});}));

OAuth2orize also bundles support for implicit token grants.

Register Exchanges

After a client has obtained an authorization grant from the user, that grant canbe exchanged for an access token.

server.exchange(oauth2orize.exchange.code(function(client,code,redirectURI,done){AuthorizationCode.findOne(code,function(err,code){if(err){returndone(err);}if(client.id!==code.clientId){returndone(null,false);}if(redirectURI!==code.redirectUri){returndone(null,false);}vartoken=utils.uid(256);varat=newAccessToken(token,code.userId,code.clientId,code.scope);at.save(function(err){if(err){returndone(err);}returndone(null,token);});});}));

OAuth2orize also bundles support for password and client credential grants.Additionally, bundled refresh token support allows expired access tokens to berenewed.

Implement Authorization Endpoint

When a client requests authorization, it will redirect the user to anauthorization endpoint. The server must authenticate the user and obtaintheir permission.

app.get('/dialog/authorize',login.ensureLoggedIn(),server.authorize(function(clientID,redirectURI,done){Clients.findOne(clientID,function(err,client){if(err){returndone(err);}if(!client){returndone(null,false);}if(client.redirectUri!=redirectURI){returndone(null,false);}returndone(null,client,client.redirectURI);});}),function(req,res){res.render('dialog',{transactionID:req.oauth2.transactionID,user:req.user,client:req.oauth2.client});});

In this example,connect-ensure-loginmiddleware is being used to make sure a user is authenticated beforeauthorization proceeds. At that point, the application renders a dialogasking the user to grant access. The resulting form submission is processedusingdecision middleware.

app.post('/dialog/authorize/decision',login.ensureLoggedIn(),server.decision());

Based on the grant type requested by the client, the appropriate grantmodule registered above will be invoked to issue an authorization code.

Session Serialization

Obtaining the user's authorization involves multiple request/response pairs.During this time, an OAuth 2.0 transaction will be serialized to the session.Client serialization functions are registered to customize this process, whichwill typically be as simple as serializing the client ID, and finding the clientby ID when deserializing.

server.serializeClient(function(client,done){returndone(null,client.id);});server.deserializeClient(function(id,done){Clients.findOne(id,function(err,client){if(err){returndone(err);}returndone(null,client);});});

Implement Token Endpoint

Once a user has approved access, the authorization grant can be exchanged by theclient for an access token.

app.post('/token',passport.authenticate(['basic','oauth2-client-password'],{session:false}),server.token(),server.errorHandler());

Passport strategies are used to authenticate theclient, in this case using either an HTTP Basic authentication header (asprovided bypassport-http) orclient credentials in the request body (as provided bypassport-oauth2-client-password).

Based on the grant type issued to the client, the appropriate exchange moduleregistered above will be invoked to issue an access token. If an error occurs,errorHandler middleware will format an error response.

Implement API Endpoints

Once an access token has been issued, a client will use it to make API requestson behalf of the user.

app.get('/api/userinfo',passport.authenticate('bearer',{session:false}),function(req,res){res.json(req.user);});

In this example, bearer tokens are issued, which are then authenticated usingan HTTP Bearer authentication header (as provided bypassport-http-bearer)

Examples

Thisexample demonstrateshow to implement an OAuth service provider, complete with protected API access.

Related Modules

Debugging

oauth2orize uses thedebug module. You can enable debugging messages on the console by doingexport DEBUG=oauth2orize before running your application.

License

The MIT License

Copyright (c) 2012-2021 Jared Hanson <https://www.jaredhanson.me/>

Packages

No packages published

Contributors21


[8]ページ先頭

©2009-2025 Movatter.jp