Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

client-oauth2

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

client-oauth2

Straight-forward library for executing OAuth 2.0 flows and making API requests.

  • 1.0.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Client OAuth 2.0

NPM version NPM downloads Build status

Straight-forward library for executing OAuth 2.0 grant flows and making API requests in node and on the browser.

Please note: This module uses Popsicle to make API requests. Promises must be supported or polyfilled on all target environments.

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.

var githubAuth = new ClientOAuth2({
  clientId: 'abc',
  clientSecret: '123',
  accessTokenUri: 'https://github.com/login/oauth/access_token',
  authorizationUri: 'https://github.com/login/oauth/authorize',
  authorizationGrants: ['credentials'],
  redirectUri: 'http://example.com/auth/github/callback',
  scopes: ['notifications', 'gist']
})
  • clientId The client id string assigned to you by the provider
  • clientSecret The client secret string assigned to you by the provider
  • accessTokenUri The url to request the access token
  • authorizationUri The url to redirect users to authenticate with the provider
  • redirectUri A custom url for the provider to redirect users back to your application
  • scopes An array of scopes to authenticate against

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
  • options Transport options from popsicle

To 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.

var token = githubAuth.createToken('access token', 'optional refresh token', 'optional token type', { optional: 'raw user data' })

// Refresh the users credentials and save the updated access token.
token.refresh().then(updateToken)

token.request({
  method: 'get',
  url: 'https://api.github.com/users'
})
  .then(function (res) {
    console.log(res) //=> { body: '...', status: 200, headers: { ... } }
  })

You can override the request mechanism if you need a custom implementation by setting githubAuth.request = function (opts) { return new Promise(...) }. You will need to make sure that the custom request mechanism supports the correct input and output objects.

Authorization Code Grant

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.

  1. Redirect user to githubAuth.code.getUri().
  2. Parse response uri and get token using githubAuth.code.getToken(uri).
var express = require('express')
var app     = express()

app.get('/auth/github', function (req, res) {
  var uri = githubAuth.code.getUri()

  res.redirect(uri)
})

app.get('/auth/github/callback', function (req, res) {
  githubAuth.code.getToken(req.url)
    .then(function (user) {
      console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }

      // Refresh the current users access token.
      user.refresh().then(function (updatedUser) {
        console.log(updatedUser === user) //=> true
      })

      // 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.
      return res.send(user.accessToken)
    })
})

Implicit Grant

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.

  1. Redirect user to githubAuth.token.getUri().
  2. Parse response uri for the access token using githubAuth.token.getToken(uri).
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.
      user.request({
        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())

Resource Owner Password Credentials Grant

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.

  1. Make a direct request for the access token on behalf of the user using githubAuth.owner.getToken(username, password).
githubAuth.owner.getToken('blakeembrey', 'hunter2')
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

Client Credentials Grant

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).

  1. Get the access token for the application by using githubAuth.credentials.getToken().
githubAuth.credentials.getToken()
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

JWT as Authorization Grant

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.

githubAuth.jwt.getToken('eyJhbGciOiJFUzI1NiJ9.eyJpc3Mi[...omitted for brevity...].J9l-ZhwP[...omitted for brevity...]')
  .then(function (user) {
    console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
  })

License

Apache 2.0

Keywords

FAQs

Package last updated on 27 Jul 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc