You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jan 20, 2024. It is now read-only.
Straight-forward execution of OAuth 2.0 flows and authenticated API requests. 7.58 kB in browsers, after minification and gzipping, 75% fromurl andquerystring dependencies.
Installation
npm install client-oauth2 --save
Usage
The 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.
P.S. The second argument to the constructor can inject a custom request function.
Options (global and method-based)
clientId The client id string assigned to you by the provider
clientSecret The client secret string assigned to you by the provider (not required fortoken)
accessTokenUri The url to request the access token (not required fortoken)
authorizationUri The url to redirect users to authenticate with the provider (only required fortoken andcode)
redirectUri A custom url for the provider to redirect users back to your application (only required fortoken andcode)
scopes An array of scopes to authenticate against
state Nonce sent back with the redirect when authorization is complete to verify authenticity (should be random for every request)
Request options
body An object to merge with the body of every request
query An object to merge with the query parameters of every request
headers An object to merge with the headers of every request
To re-create an access token instance and make requests on behalf on the user, you can create an access token instance by using thecreateToken method on a client instance.
// Can also just pass the raw `data` object in place of an argument.vartoken=githubAuth.createToken('access token','optional refresh token','optional token type',{data:'raw user data'})// Set the token TTL.token.expiresIn(1234)// Seconds.token.expiresIn(newDate('2016-11-08'))// Date.// Refresh the users credentials and save the new access token and info.token.refresh().then(storeNewToken)// Sign a standard HTTP request object, updating the URL with the access token// or adding authorization headers, depending on token type.token.sign({method:'get',url:'https://api.github.com/users'})//=> { method, url, headers, ... }
P.S. All authorization methods acceptoptions as the last argument, useful for overriding the global configuration on a per-request basis.
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.
Redirect user togithubAuth.code.getUri([ options ]).
Parse response uri and get token usinggithubAuth.code.getToken(uri [, options ]).
varexpress=require('express')varapp=express()app.get('/auth/github',function(req,res){varuri=githubAuth.code.getUri()res.redirect(uri)})app.get('/auth/github/callback',function(req,res){githubAuth.code.getToken(req.originalUrl).then(function(user){console.log(user)//=> { accessToken: '...', tokenType: 'bearer', ... }// Refresh the current users access token.user.refresh().then(function(updatedUser){console.log(updatedUser!==user)//=> trueconsole.log(updatedUser.accessToken)})// Sign API requests on behalf of the current user.user.sign({method:'get',url:'http://example.com'})// We should store the token into a database.returnres.send(user.accessToken)})})
P.S. ThegetToken URI parameter can be an object containingpathname andquery properties.
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.
Redirect user togithubAuth.token.getUri([ options ]).
Parse response uri for the access token usinggithubAuth.token.getToken(uri [, options ]).
window.oauth2Callback=function(uri){githubAuth.token.getToken(uri).then(function(user){console.log(user)//=> { accessToken: '...', tokenType: 'bearer', ... }// Make a request to the github API for the current user.returnpopsicle.request(user.sign({method:'get',url:'https://api.github.com/user'})).then(function(res){console.log(res)//=> { body: { ... }, status: 200, headers: { ... }}})})}// Open the page in a new window, then redirect back to a page that calls our global `oauth2Callback` function.window.open(githubAuth.token.getUri())
P.S. ThegetToken URI parameter can be an object containingpathname,query andhash properties.
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.
Make a direct request for the access token on behalf of the user usinggithubAuth.owner.getToken(username, password [, options ]).
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).
Get the access token for the application by usinggithubAuth.credentials.getToken([ options ]).
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.
Get the access token for the application by usinggithubAuth.jwt.getToken(jwt [, options ]).
githubAuth.jwt.getToken('eyJhbGciOiJFUzI1NiJ9.eyJpc3Mi[...omitted for brevity...].J9l-ZhwP[...omitted for brevity...]').then(function(user){console.log(user)//=> { accessToken: '...', tokenType: 'bearer', ... }})
Dependencies
Requires an ES5 environment with globalPromise andObject.assign.
License
Apache 2.0
About
A JavaScript implementation of an oauth2 client, for inclusion in the JavaScript client generator for APIs described with RAML.