What is client-oauth2?
The client-oauth2 npm package is a client-side library for handling OAuth2 authentication flows. It supports various OAuth2 flows including Authorization Code, Implicit, Resource Owner Password Credentials, and Client Credentials. This package is useful for applications that need to interact with OAuth2-compliant services for authentication and authorization.
What are client-oauth2's main functionalities?
Authorization Code Flow
This feature demonstrates how to use the Authorization Code Flow with GitHub as the OAuth2 provider. It includes setting up the client with necessary URIs and scopes, redirecting the user to the authorization page, and handling the callback to obtain the access token.
const ClientOAuth2 = require('client-oauth2');
const 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']
});
// Redirect the user to the authorization page
const uri = githubAuth.code.getUri();
// After the user is redirected back to your callback URL
githubAuth.code.getToken(window.location.href)
.then(function (user) {
console.log(user);
});
Implicit Flow
This feature demonstrates how to use the Implicit Flow with GitHub as the OAuth2 provider. It includes setting up the client with necessary URIs and scopes, redirecting the user to the authorization page, and handling the callback to obtain the access token directly from the URL.
const ClientOAuth2 = require('client-oauth2');
const githubAuth = new ClientOAuth2({
clientId: 'abc',
authorizationUri: 'https://github.com/login/oauth/authorize',
redirectUri: 'http://example.com/auth/github/callback',
scopes: ['notifications', 'gist']
});
// Redirect the user to the authorization page
const uri = githubAuth.token.getUri();
// After the user is redirected back to your callback URL
githubAuth.token.getToken(window.location.href)
.then(function (user) {
console.log(user);
});
Resource Owner Password Credentials Flow
This feature demonstrates how to use the Resource Owner Password Credentials Flow with GitHub as the OAuth2 provider. It includes setting up the client with necessary URIs and scopes, and obtaining the access token using the user's username and password.
const ClientOAuth2 = require('client-oauth2');
const githubAuth = new ClientOAuth2({
clientId: 'abc',
clientSecret: '123',
accessTokenUri: 'https://github.com/login/oauth/access_token',
scopes: ['notifications', 'gist']
});
// Get the user token using username and password
githubAuth.owner.getToken('username', 'password')
.then(function (user) {
console.log(user);
});
Client Credentials Flow
This feature demonstrates how to use the Client Credentials Flow with GitHub as the OAuth2 provider. It includes setting up the client with necessary URIs and scopes, and obtaining the access token using the client credentials.
const ClientOAuth2 = require('client-oauth2');
const githubAuth = new ClientOAuth2({
clientId: 'abc',
clientSecret: '123',
accessTokenUri: 'https://github.com/login/oauth/access_token',
scopes: ['notifications', 'gist']
});
// Get the client token
githubAuth.credentials.getToken()
.then(function (user) {
console.log(user);
});
Other packages similar to client-oauth2
simple-oauth2
The simple-oauth2 package is a comprehensive library for handling OAuth2 authentication flows. It supports all standard OAuth2 flows and provides a more extensive set of features compared to client-oauth2, including token management and automatic token refresh.
passport-oauth2
The passport-oauth2 package is a strategy for the Passport authentication middleware. It allows applications to authenticate using OAuth2 by leveraging the Passport ecosystem, which provides a wide range of authentication strategies and integrations.
axios-oauth-client
The axios-oauth-client package is a lightweight library that integrates OAuth2 authentication with the popular Axios HTTP client. It simplifies the process of making authenticated HTTP requests by automatically handling token acquisition and renewal.
Client OAuth 2.0
![Build status](https://img.shields.io/travis/mulesoft/js-client-oauth2.svg?style=flat)
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',
authorizationGrants: ['credentials'],
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
- transport Change certain request transport behaviour (currently
rejectUnauthorized
and agent
)
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', { data: 'raw user data' })
token.refresh().then(storeNewToken)
token.sign({
method: 'get',
url: 'https://api.github.com/users'
})
P.S. All authorization methods accept options
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 to
githubAuth.code.getUri([ options ])
. - 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)
user.refresh().then(function (updatedUser) {
console.log(updatedUser !== user)
console.log(updatedUser.accessToken)
})
user.sign({
method: 'get',
url: 'http://example.com'
})
return res.send(user.accessToken)
})
})
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 to
githubAuth.token.getUri([ options ])
. - 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)
user.request({
method: 'get',
url: 'https://api.github.com/user'
}).then(function (res) {
console.log(res)
})
})
}
window.open(githubAuth.token.getUri())
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 using
githubAuth.owner.getToken(username, password [, options ])
.
githubAuth.owner.getToken('blakeembrey', 'hunter2')
.then(function (user) {
console.log(user)
})
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 using
githubAuth.credentials.getToken([ options ])
.
githubAuth.credentials.getToken()
.then(function (user) {
console.log(user)
})
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 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)
})
License
Apache 2.0