UNPKG

8.14 kBMarkdownView Raw
1# Client OAuth 2.0
2
3[![NPM version][npm-image]][npm-url]
4[![NPM downloads][downloads-image]][downloads-url]
5[![Build status][travis-image]][travis-url]
6
7> Straight-forward execution of OAuth 2.0 flows and authenticated API requests. 7.58 kB in browsers, after minification and gzipping, 75% from `url` and `querystring` dependencies.
8
9## Installation
10
11```sh
12npm install client-oauth2 --save
13```
14
15## Usage
16
17The module supports executing all the various OAuth 2.0 flows in any JavaScript environment. To authenticate you need to create an instance of the module for your API.
18
19```javascript
20var ClientOAuth2 = require('client-oauth2')
21
22var githubAuth = new ClientOAuth2({
23 clientId: 'abc',
24 clientSecret: '123',
25 accessTokenUri: 'https://github.com/login/oauth/access_token',
26 authorizationUri: 'https://github.com/login/oauth/authorize',
27 authorizationGrants: ['credentials'],
28 redirectUri: 'http://example.com/auth/github/callback',
29 scopes: ['notifications', 'gist']
30})
31```
32
33**P.S.** The second argument to the constructor can inject a custom request function.
34
35### Options (global and method-based)
36
37* **clientId** The client id string assigned to you by the provider
38* **clientSecret** The client secret string assigned to you by the provider (not required for `token`)
39* **accessTokenUri** The url to request the access token (not required for `token`)
40* **authorizationUri** The url to redirect users to authenticate with the provider (only required for `token` and `code`)
41* **redirectUri** A custom url for the provider to redirect users back to your application (only required for `token` and `code`)
42* **scopes** An array of scopes to authenticate against
43* **state** Nonce sent back with the redirect when authorization is complete to verify authenticity (should be random for every request)
44
45### Request options
46
47* **body** An object to merge with the body of every request
48* **query** An object to merge with the query parameters of every request
49* **headers** An object to merge with the headers of every request
50
51To re-create an access token instance and make requests on behalf on the user, you can create an access token instance by using the `createToken` method on a client instance.
52
53```javascript
54// Can also just pass the raw `data` object in place of an argument.
55var token = githubAuth.createToken('access token', 'optional refresh token', 'optional token type', { data: 'raw user data' })
56
57// Refresh the users credentials and save the updated access token.
58token.refresh().then(storeNewToken)
59
60// Sign a standard HTTP request object, updating URL with token or authorization headers.
61token.sign({
62 method: 'get',
63 url: 'https://api.github.com/users'
64}) //=> { method, url, headers, ... }
65```
66
67**P.S.** All authorization methods accept `options` as the last argument, useful for overriding the global configuration on a per-request basis.
68
69### [Authorization Code Grant](http://tools.ietf.org/html/rfc6749#section-4.1)
70
71> The authorization code grant type is used to obtain both access tokens and refresh tokens and is optimized for confidential clients. Since this is a redirection-based flow, the client must be capable of interacting with the resource owner's user-agent (typically a web browser) and capable of receiving incoming requests (via redirection) from the authorization server.
72
731. Redirect user to `githubAuth.code.getUri([ options ])`.
742. Parse response uri and get token using `githubAuth.code.getToken(uri [, options ])`.
75
76```javascript
77var express = require('express')
78var app = express()
79
80app.get('/auth/github', function (req, res) {
81 var uri = githubAuth.code.getUri()
82
83 res.redirect(uri)
84})
85
86app.get('/auth/github/callback', function (req, res) {
87 githubAuth.code.getToken(req.originalUrl)
88 .then(function (user) {
89 console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
90
91 // Refresh the current users access token.
92 user.refresh().then(function (updatedUser) {
93 console.log(updatedUser !== user) //=> true
94 console.log(updatedUser.accessToken)
95 })
96
97 // Sign API requests on behalf of the current user.
98 user.sign({
99 method: 'get',
100 url: 'http://example.com'
101 })
102
103 // We should store the token into a database.
104 return res.send(user.accessToken)
105 })
106})
107```
108
109### [Implicit Grant](http://tools.ietf.org/html/rfc6749#section-4.2)
110
111> The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript.
112
1131. Redirect user to `githubAuth.token.getUri([ options ])`.
1142. Parse response uri for the access token using `githubAuth.token.getToken(uri [, options ])`.
115
116```javascript
117window.oauth2Callback = function (uri) {
118 githubAuth.token.getToken(uri)
119 .then(function (user) {
120 console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
121
122 // Make a request to the github API for the current user.
123 user.request({
124 method: 'get',
125 url: 'https://api.github.com/user'
126 }).then(function (res) {
127 console.log(res) //=> { body: { ... }, status: 200, headers: { ... } }
128 })
129 })
130}
131
132// Open the page in a new window, then redirect back to a page that calls our global `oauth2Callback` function.
133window.open(githubAuth.token.getUri())
134```
135
136### [Resource Owner Password Credentials Grant](http://tools.ietf.org/html/rfc6749#section-4.3)
137
138> The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authorization server should take special care when enabling this grant type and only allow it when other flows are not viable.
139
1401. Make a direct request for the access token on behalf of the user using `githubAuth.owner.getToken(username, password [, options ])`.
141
142```javascript
143githubAuth.owner.getToken('blakeembrey', 'hunter2')
144 .then(function (user) {
145 console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
146 })
147```
148
149### [Client Credentials Grant](http://tools.ietf.org/html/rfc6749#section-4.4)
150
151> The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control, or those of another resource owner that have been previously arranged with the authorization server (the method of which is beyond the scope of this specification).
152
1531. Get the access token for the application by using `githubAuth.credentials.getToken([ options ])`.
154
155```javascript
156githubAuth.credentials.getToken()
157 .then(function (user) {
158 console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
159 })
160```
161
162### [JWT as Authorization Grant](https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12#section-2.1)
163
164> A JSON Web Token (JWT) Bearer Token can be used to request an access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature or Message Authentication Code calculated over) the JWT, without a direct user approval step at the authorization server.
165
1661. Get the access token for the application by using `githubAuth.jwt.getToken(jwt [, options ])`.
167
168```javascript
169githubAuth.jwt.getToken('eyJhbGciOiJFUzI1NiJ9.eyJpc3Mi[...omitted for brevity...].J9l-ZhwP[...omitted for brevity...]')
170 .then(function (user) {
171 console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
172 })
173```
174
175## License
176
177Apache 2.0
178
179[npm-image]: https://img.shields.io/npm/v/client-oauth2.svg?style=flat
180[npm-url]: https://npmjs.org/package/client-oauth2
181[downloads-image]: https://img.shields.io/npm/dm/client-oauth2.svg?style=flat
182[downloads-url]: https://npmjs.org/package/client-oauth2
183[travis-image]: https://img.shields.io/travis/mulesoft/js-client-oauth2.svg?style=flat
184[travis-url]: https://travis-ci.org/mulesoft/js-client-oauth2