• Stars
    star
    532
  • Rank 83,356 (Top 2 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript implementation of an oauth2 client, for inclusion in the JavaScript client generator for APIs described with RAML.

Client OAuth 2.0

NPM version NPM downloads Build status Greenkeeper badge

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.

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 ClientOAuth2 = require('client-oauth2')

var githubAuth = new ClientOAuth2({
  clientId: 'abc',
  clientSecret: '123',
  accessTokenUri: 'https://github.com/login/oauth/access_token',
  authorizationUri: 'https://github.com/login/oauth/authorize',
  redirectUri: 'http://example.com/auth/github/callback',
  scopes: ['notifications', 'gist']
})

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 for token)
  • accessTokenUri The url to request the access token (not required for token)
  • authorizationUri The url to redirect users to authenticate with the provider (only required for token and code)
  • redirectUri A custom url for the provider to redirect users back to your application (only required for token and code)
  • 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 the createToken method on a client instance.

// Can also just pass the raw `data` object in place of an argument.
var token = githubAuth.createToken('access token', 'optional refresh token', 'optional token type', { data: 'raw user data' })

// Set the token TTL.
token.expiresIn(1234) // Seconds.
token.expiresIn(new Date('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 accept options as the last argument, useful for overriding the global configuration on a per-request basis.

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([ options ]).
  2. Parse response uri and get token using githubAuth.code.getToken(uri [, options ]).
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.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) //=> true
        console.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.
      return res.send(user.accessToken)
    })
})

P.S. The getToken URI parameter can be an object containing pathname and query properties.

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([ options ]).
  2. Parse response uri for the access token using githubAuth.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.
      return popsicle.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. The getToken URI parameter can be an object containing pathname, query and hash properties.

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 [, options ]).
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([ options ]).
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.

  1. Get the access token for the application by using githubAuth.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 global Promise and Object.assign.

License

Apache 2.0

More Repositories

1

raml-for-jax-rs

This project is all about two way transformation of JAX-RS-annotated Java code to RAML API description and back.
Java
293
star
2

raml-client-generator

Template-driven generator of clients for APIs described by a RAML spec
JavaScript
121
star
3

osprey-mock-service

Generate an API mock service from a RAML definition using Osprey
JavaScript
110
star
4

yaml-ast-parser

This is a fork of JS-YAML which supports parsing of YAML into AST
TypeScript
79
star
5

data-weave-cli

DataWeave CLI and Native Library
Scala
77
star
6

rhinodo

Execute Node modules in the JVM (powered by Rhino)
Java
51
star
7

raml-sublime-plugin

Syntax highlighter for the RESTful API Modeling Language
RAML
49
star
8

raml-jaxrs-codegen

Tools to enable RAML-first development in JAX-RS projects
Java
40
star
9

quartz-mongodb

Mongo DB JobStore for Quartz
Java
37
star
10

raml-java-client-generator

Raml Java Client Generator
Java
34
star
11

net-tools-api

Simple API with network tools like ping and traceroute
HTML
33
star
12

raml-javascript-generator

Generate a JavaScript API client from RAML
TypeScript
32
star
13

raml-generator

Generate files from a RAML document and Handlebars templates
RAML
31
star
14

keycloak-duo-spi

Keycloak integration for Duo Security MFA
Java
29
star
15

json-ld-schema

JSON Schema/SHACL based validation of JSON-LD documents
TypeScript
28
star
16

swagger-to-raml-object

This repository is deprecated! Please use the official oas-raml-converter instead.
JavaScript
26
star
17

mule-gradle-plugin

Plugin for building mule apps with the gradle build system.
Groovy
24
star
18

raml-java-tools

Java
19
star
19

graphql-router

Router to expose services as graphql
Java
19
star
20

node-raml-validate

Strict validation of RAML parameters in JavaScript
JavaScript
17
star
21

data-weave-intellij-plugin

An intellij plugin that adds support for DataWeave 2.0
Java
15
star
22

osprey-method-handler

Middleware for validating requests and responses based on a RAML method object
JavaScript
15
star
23

json-form

dynamic angular forms generated from a json
JavaScript
15
star
24

api-console-cli

A CLI tools for the API console.
JavaScript
14
star
25

raml-tutorial-200

Step by step 200 raml tutorial code
14
star
26

jenkins-job-examples

13
star
27

exchange-documentation-samples

RAML
13
star
28

gRPC-Connect

Set of tools and plugins to create OOTB Mule 4 Connectors from Protobuf definitions and connect agains gRPC Servers
Java
13
star
29

data-weave-rfc

RFC for the data weave language
10
star
30

data-weave-sample-module

Example DataWeave Module
DataWeave
10
star
31

data-weave-language-server

The DataWeave Language Server
10
star
32

data-weave-tutorial

DataWeave
10
star
33

log4j2-migrator

Script to migrate log4j configurations to log4j2
Groovy
8
star
34

smart-connectors-integration-tests

bundle with smart connectors and apps using them.
DataWeave
7
star
35

dataweave-cookbook

Recepies For DataWeave
7
star
36

data-weave-custom-data-format

Example for creating custom data format
DataWeave
7
star
37

muleadore64

Mulesoft ❤️'s Commodore64
JavaScript
7
star
38

mule-module-dynamic-flows

Java
7
star
39

mql

Mashup Query Language
Java
6
star
40

mule-match

A simple swapping app to use as a Reference app for React applications.
JavaScript
6
star
41

github-cla-webhook

Automate CLA verification for open source repositories using GitHub issues
JavaScript
6
star
42

ts-structure-parser

Structural Parser for Typescript files, provides JSON object with a declarations structures
TypeScript
6
star
43

jshint-java

Thin Java layer over Node-JSHint
Java
6
star
44

aws-lambda

AWS Lambda Connector for Mule 4.x
Java
5
star
45

raml-object-standard

A standardized JSON schema for RAML
JavaScript
5
star
46

Testfull6

Apex
5
star
47

mule-module-restlet

Restlet support for Mule
Java
4
star
48

configuration-service

Connector to implement Configuration as a Service in Mule Apps
Java
4
star
49

mule-docs-builder

Code for building the new MuleSoft documentation site.
HTML
4
star
50

spring-cloud-config-connector

Module to take advantage of spring cloud config in MuleESB
Java
4
star
51

rtf-utilities

Shell
4
star
52

node-raml-sanitize

Sanitization of RAML parameters into strict values in JavaScript
JavaScript
4
star
53

mule-module-selenium

Mule Selenium Module accepts commands and sends them to a browser. This is implemented internally using Selenium WebDriver, which sends commands to a browser, and retrieves results. Most browser drivers actually launch and access a browser application (such as Firefox or Internet Explorer); there is also a HtmlUnit browser driver, which simulates a browser using HtmlUnit.
Java
4
star
54

hue-connector

Connects to the Philips Hue lighting system
Java
4
star
55

raml-object-to-raml

Takes a RAML object in JavaScript, specifically having the same structure of the output of the RAML JavaScript parser, and emits properly-formatted RAML (text).
JavaScript
4
star
56

docker

Repository with docker files for mule
Shell
3
star
57

aws-lambda-connector

MuleSoft connector for Amazon AWS Lambda
Java
3
star
58

raml-suggestions

RAML suggestions module for IDEs
TypeScript
3
star
59

mule-module-activiti-examples

Mule Activiti Examples
Java
3
star
60

data-weave-grimoire

Set of magic spells
JavaScript
3
star
61

grpc-connector

Experimental connector for gRPC
Java
3
star
62

oddish

scripts that make your life easier
JavaScript
3
star
63

data-weave-tmLanguage

DataWeave 2.0 tmLanguage
DataWeave
3
star
64

freemarker-transformer

FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates.
Java
3
star
65

core-concept-examples

Core Concept Examples
Java
3
star
66

api-standards

API standards RAML library
RAML
3
star
67

api-console-builder

A module to build a minified and concatenated file for the API console
JavaScript
3
star
68

raml-json-validation

JavaScript
3
star
69

example-connector

Java
3
star
70

recess-maven-plugin

Java
3
star
71

devkit-documentation-rest-jersey

A simple project to show how to create a Connector for a RESTful Service using Jersey Client
Java
3
star
72

osprey-router

Simple middleware-style router for RAML based on router
JavaScript
3
star
73

mock-maven-repository

Test utility to create ephemeral maven repository and artifacts to perform tests
Java
2
star
74

api-platform-raml-import

JavaScript
2
star
75

flareon

React component for shortcut management.
JavaScript
2
star
76

raml-actions

TypeScript
2
star
77

jmh-influx-report

Creates jmh into influx db
Java
2
star
78

design-system

JavaScript
2
star
79

newrelic-plugins

Newrelic Plugins
Java
2
star
80

raml-xml-validation

XML validation API for RAML JS parser
JavaScript
2
star
81

cargo-mule-container

Java
2
star
82

jenkins-docker

Shell
2
star
83

api-console-sources-resolver

A module to download Mulesoft's API console sources.
JavaScript
2
star
84

vscode-raml-ide

TypeScript
2
star
85

flickr-connector

Cloud Connector for Flickr
Java
2
star
86

connector-certification-tools

Java
2
star
87

video-face-detection

JavaScript
2
star
88

mule-module-shiro

Shiro Security support for Mule
Java
2
star
89

connector-documentation-oauth2-example

A simple project to show how to create a Connector for a Service that use OAuth2 as Authentication mechanism
Java
2
star
90

raml-box-upload-api

2
star
91

data-weave-playground-ui

The UI of the playground
TypeScript
2
star
92

mule-jaas

Javadoc as a Service
Java
2
star
93

mulesoft-lights-demo

Demo setup in the office featuring Twitter, Hue lights, and Mule
2
star
94

mule-hr-service

2
star
95

osprey-resources

Automatically support RAML resources
JavaScript
2
star
96

mule-module-twiml

A Mule module for generating Twilios Markup Language. Twilio can handle instructions for calls and SMS messages in * real time from iON applications. When an SMS or incoming call is received, Twilio looks up the iON app associated * with the phone number called and makes a request to it. iON will respond to the request and that response will * decides how the call should proceed by returning a Twilio Markup XML (TwiML) document telling Twilio to say text * to the caller, send an SMS message, play audio files, get input from the keypad, record audio, connect the call * to another phone and more.
Java
2
star
97

groovy-beta-enviroments

Groovy Class to Create Enviroments in Beta Enviroments
Groovy
1
star
98

mule-deployment-plugin

Java
1
star
99

raml-json-enhance-node

A RAML's JSON enhancer node package for the API Console
RAML
1
star
100

maven-connector

Mule Maven Connector
Java
1
star