UNPKG

8.21 kBMarkdownView Raw
1# Simple OAuth2
2
3Node.js client library for [Oauth2](http://oauth.net/2/).
4
5OAuth2 lets users grant the access to the desired resources to third party applications,
6giving them the possibility to enable and disable those accesses whenever they want.
7
8Simple OAuth2 supports the following flows.
9
10* Authorization Code Flow (for apps with servers that can store persistent information).
11* Password Credentials (when previous flow can't be used or during development).
12* [Client Credentials Flow](http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4) (the client can request an access token using only its client credentials)
13
14## Requirements
15
16Node client library is tested against Node ~0.8.x
17
18
19## Installation
20
21Install the client library using [npm](http://npmjs.org/):
22
23 $ npm install simple-oauth2
24
25Install the client library using git:
26
27 $ git clone git://github.com/andreareginato/simple-oauth2.git
28 $ cd simple-oauth2
29 $ npm install
30
31
32## Getting started
33
34### Express and Github example
35
36```javascript
37var express = require('express'),
38 app = express();
39
40var OAuth2 = require('simple-oauth2')({
41 clientID: CLIENT_ID,
42 clientSecret: CLIENT_SECRET,
43 site: 'https://github.com/login',
44 tokenPath: '/oauth/access_token'
45});
46
47// Authorization uri definition
48var authorization_uri = OAuth2.AuthCode.authorizeURL({
49 redirect_uri: 'http://localhost:3000/callback',
50 scope: 'notifications',
51 state: '3(#0/!~'
52});
53
54// Initial page redirecting to Github
55app.get('/auth', function (req, res) {
56 res.redirect(authorization_uri);
57});
58
59// Callback service parsing the authorization token and asking for the access token
60app.get('/callback', function (req, res) {
61 var code = req.query.code;
62 console.log('/callback');
63 OAuth2.AuthCode.getToken({
64 code: code,
65 redirect_uri: 'http://localhost:3000/callback'
66 }, saveToken);
67
68 function saveToken(error, result) {
69 if (error) { console.log('Access Token Error', error.message); }
70 token = OAuth2.AccessToken.create(result);
71 }
72});
73
74app.get('/', function (req, res) {
75 res.send('Hello World');
76});
77
78app.listen(3000);
79
80console.log('Express server started on port 3000');
81```
82
83Credits to [@lazybean](https://github.com/lazybean)
84
85### Authorization Code flow
86
87The Authorization Code flow is made up from two parts. At first your application asks to
88the user the permission to access their data. If the user approves the OAuth2 server sends
89to the client an authorization code. In the second part, the client POST the authorization code
90along with its client secret to the Lelylan in order to get the access token.
91
92```javascript
93// Set the client credentials and the OAuth2 server
94var credentials = {
95 clientID: '<client-id>',
96 clientSecret: '<client-secret>',
97 site: 'https://api.oauth.com'
98};
99
100// Initialize the OAuth2 Library
101var OAuth2 = require('simple-oauth2')(credentials);
102
103// Authorization OAuth2 URI
104var authorization_uri = OAuth2.AuthCode.authorizeURL({
105 redirect_uri: 'http://localhost:3000/callback',
106 scope: '<scope>',
107 state: '<state>'
108});
109
110// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
111res.redirect(authorization_uri);
112
113// Get the access token object (the authorization code is given from the previous step).
114var token;
115OAuth2.AuthCode.getToken({
116 code: '<code>',
117 redirect_uri: 'http://localhost:3000/callback'
118}, saveToken);
119
120// Save the access token
121function saveToken(error, result) {
122 if (error) { console.log('Access Token Error', error.message); }
123 token = OAuth2.AccessToken.create(result);
124});
125```
126
127
128### Password Credentials Flow
129
130This flow is suitable when the resource owner has a trust relationship with the
131client, such as its computer operating system or a highly privileged application.
132Use this flow only when other flows are not viable or when you need a fast way to
133test your application.
134
135```javascript
136// Get the access token object.
137var token;
138OAuth2.Password.getToken({
139 username: 'username',
140 password: 'password' 
141}, saveToken);
142
143// Save the access token
144function saveToken(error, result) {
145 if (error) { console.log('Access Token Error', error.message); }
146 token = OAuth2.AccessToken.create(result);
147
148 OAuth2.api('GET', '/users', {
149 access_token: token.token.access_token
150 }, function (err, data) {
151 console.log(data);
152 });
153});
154```
155
156### Client Credentials Flow
157
158This flow is suitable when client is requesting access to the protected resources under its control.
159
160```javascript
161// Get the access token object.
162var token;
163var credentials = {
164 clientID: '<client-id>',
165 clientSecret: '<client-secret>',
166 site: 'https://api.oauth.com'
167};
168
169// Initialize the OAuth2 Library
170var OAuth2 = require('simple-oauth2')(credentials);
171
172// Get the access token object for the client
173OAuth2.Client.getToken(saveToken);
174
175// Save the access token
176function saveToken(error, result) {
177 if (error) { console.log('Access Token Error', error.message); }
178 token = OAuth2.AccessToken.create(result);
179});
180```
181
182### Access Token object
183
184When a token expires we need to refresh it. Simple OAuth2 offers the
185AccessToken class that add a couple of useful methods to refresh the
186access token when it is expired.
187
188```javascript
189// Sample of a JSON access token (you got it through previous steps)
190var token = {
191 'access_token': '<access-token>',
192 'refresh_token': '<refresh-token>',
193 'expires_in': '7200'
194};
195
196// Create the access token wrapper
197var token = OAuth2.AccessToken.create(token);
198
199// Check if the token is expired. If expired it is refreshed.
200if (token.expired()) {
201 token.refresh(function(error, result) {
202 token = result;
203 })
204}
205```
206
207
208### Errors
209
210Exceptions are raised when a 4xx or 5xx status code is returned.
211
212 HTTPError
213
214Through the error message attribute you can access the JSON representation
215based on HTTP `status` and error `message`.
216
217```javascript
218OAuth2.AuthCode.getToken(function(error, token) {
219 if (error) { console.log(error.message); }
220});
221// => { "status": "401", "message": "Unauthorized" }
222```
223
224
225### Configurations
226
227Simple OAuth2 accepts an object with the following valid params.
228
229* `clientID` - Required registered Client ID.
230* `clientSecret` - Required registered Client secret.
231* `site` - Required OAuth2 server site.
232* `authorizationPath` - Authorization path for the OAuth2 server. Defaults to `/oauth/authorize`.
233* `tokenPath` - Access token path for the OAuth2 server. Defaults to `/oauth/token`.
234* `useBasicAuthorizationHeader` - Whether or not the `Authorization: Basic ...` header is set on the request.
235Defaults to `true`.
236* `clientSecretParameterName` - Parameter name for the client secret. Defaults to `client_secret`.
237
238```javascript
239// Set the configuration settings
240var credentials = {
241 clientID: '<client-id>',
242 clientSecret: '<client-secret>',
243 site: 'https://www.oauth2.com',
244 authorizationPath: '/oauth2/authorization',
245 tokenPath: '/oauth2/access_token'
246};
247
248// Initialize the OAuth2 Library
249var OAuth2 = require('simple-oauth2')(credentials);
250```
251
252
253## Contributing
254
255Fork the repo on github and send a pull requests with topic branches. Do not forget to
256provide specs to your contribution.
257
258
259### Running specs
260
261* Fork and clone the repository (`dev` branch).
262* Run `npm install` for dependencies.
263* Run `make test` to execute all specs.
264* Run `make test-watch` to auto execute all specs when a file change.
265
266
267## Coding guidelines
268
269Follow [github](https://github.com/styleguide/) guidelines.
270
271
272## Feedback
273
274Use the [issue tracker](http://github.com/andreareginato/simple-oauth2/issues) for bugs.
275[Mail](mailto:andrea.reginato@.gmail.com) or [Tweet](http://twitter.com/andreareginato) us
276for any idea that can improve the project.
277
278
279## Links
280
281* [GIT Repository](http://github.com/andreareginato/simple-oauth2)
282* [Documentation](http://andreareginato.github.com/simple-oauth2)
283
284
285## Authors
286
287[Andrea Reginato](http://twitter.com/andreareginato)
288
289
290## Contributors
291
292Special thanks to the following people for submitting patches.
293
294
295## Changelog
296
297See [CHANGELOG](https://github.com/andreareginato/simple-oauth2/blob/master/CHANGELOG.md)
298
299
300## Copyright
301
302Copyright (c) 2013 [Lelylan](http://lelylan.com).
303
304This project is released under the [MIT License](http://opensource.org/licenses/MIT).