AppAuth-JS
JavaScript client SDK for communicating with OAuth 2.0 and OpenID Connect providers.
Top Related Projects
iOS and macOS SDK for communicating with OAuth 2.0 and OpenID Connect providers.
OAuth 2 / OpenID Connect Client API for JavaScript Runtimes
OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications
Microsoft Authentication Library (MSAL) for JS
Open Source Identity and Access Management For Modern Applications and Services
Quick Overview
AppAuth-JS is a client SDK for implementing OAuth 2.0 and OpenID Connect in JavaScript applications. It provides a robust, secure, and standards-compliant solution for authentication and authorization in web and mobile applications, supporting various OAuth 2.0 flows and OpenID Connect features.
Pros
- Implements OAuth 2.0 and OpenID Connect standards, ensuring compatibility with a wide range of identity providers
- Supports multiple platforms, including browser-based applications, Node.js, and React Native
- Provides built-in security features, such as PKCE (Proof Key for Code Exchange) and state management
- Actively maintained and backed by the OpenID Foundation
Cons
- Learning curve may be steep for developers new to OAuth 2.0 and OpenID Connect concepts
- Documentation could be more comprehensive, especially for advanced use cases
- Limited built-in UI components, requiring developers to implement their own user interfaces
- Some users report occasional issues with TypeScript definitions
Code Examples
- Initializing the AuthorizationServiceConfiguration:
import { AuthorizationServiceConfiguration } from '@openid/appauth';
const config = await AuthorizationServiceConfiguration.fetchFromIssuer('https://accounts.google.com');
- Creating an AuthorizationRequest:
import { AuthorizationRequest } from '@openid/appauth';
const request = new AuthorizationRequest({
client_id: 'client_id',
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile email',
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
});
- Handling the authorization response:
import { AuthorizationResponse, AuthorizationError } from '@openid/appauth';
const handleCallback = (url) => {
const result = AuthorizationResponse.parse(url);
if (result instanceof AuthorizationResponse) {
// Handle successful authorization
console.log('Authorization Code:', result.code);
} else if (result instanceof AuthorizationError) {
// Handle authorization error
console.error('Error:', result.error);
}
};
Getting Started
-
Install the package:
npm install @openid/appauth
-
Import and initialize the configuration:
import { AuthorizationServiceConfiguration, AuthorizationRequest } from '@openid/appauth'; const config = await AuthorizationServiceConfiguration.fetchFromIssuer('https://your-identity-provider.com'); const request = new AuthorizationRequest({ client_id: 'your_client_id', redirect_uri: 'https://your-app.com/callback', scope: 'openid profile email', response_type: AuthorizationRequest.RESPONSE_TYPE_CODE, });
-
Initiate the authorization flow:
const authorizationHandler = new RedirectRequestHandler(); authorizationHandler.performAuthorizationRequest(config, request);
-
Handle the callback in your redirect URI:
const result = AuthorizationResponse.parse(window.location.href); if (result instanceof AuthorizationResponse) { // Process the authorization response } else { // Handle the error }
Competitor Comparisons
iOS and macOS SDK for communicating with OAuth 2.0 and OpenID Connect providers.
Pros of AppAuth-iOS
- Native iOS implementation, optimized for performance and system integration
- Seamless integration with iOS-specific features like ASWebAuthenticationSession
- Robust support for iOS-specific security features and keychain integration
Cons of AppAuth-iOS
- Limited to iOS platform, not suitable for cross-platform development
- Requires knowledge of Swift or Objective-C for implementation
- May require more frequent updates to keep up with iOS changes
Code Comparison
AppAuth-iOS (Swift):
let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint, tokenEndpoint: tokenEndpoint)
let request = OIDAuthorizationRequest(configuration: configuration,
clientId: clientID,
scopes: [OIDScopeOpenID, OIDScopeProfile],
redirectURL: redirectURI,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
AppAuth-JS (JavaScript):
const config = await AuthorizationServiceConfiguration.fetchFromIssuer(issuerUrl);
const request = new AuthorizationRequest({
client_id: clientId,
redirect_uri: redirectUri,
scope: 'openid profile',
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
});
Both libraries provide similar functionality for OAuth 2.0 and OpenID Connect, but AppAuth-iOS is tailored for iOS development, while AppAuth-JS offers cross-platform compatibility for web and mobile applications using JavaScript.
OAuth 2 / OpenID Connect Client API for JavaScript Runtimes
Pros of openid-client
- More comprehensive OpenID Connect support, including advanced features like dynamic client registration and session management
- Better TypeScript support with full type definitions
- More active development and frequent updates
Cons of openid-client
- Steeper learning curve due to more complex API
- Larger bundle size, which may impact performance in browser environments
Code Comparison
AppAuth-JS:
const authClient = new AuthorizationServiceConfiguration({
authorizationEndpoint: 'https://example.com/auth',
tokenEndpoint: 'https://example.com/token'
});
const request = new AuthorizationRequest({
client_id: 'client_id',
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile'
});
openid-client:
const client = new Issuer({
issuer: 'https://example.com',
authorization_endpoint: 'https://example.com/auth',
token_endpoint: 'https://example.com/token'
}).Client({
client_id: 'client_id',
redirect_uris: ['https://app.example.com/callback'],
response_types: ['code']
});
const authorizationUrl = client.authorizationUrl({
scope: 'openid profile'
});
Both libraries provide OpenID Connect implementations for JavaScript, but openid-client offers more advanced features and better TypeScript support. AppAuth-JS has a simpler API and smaller bundle size, making it potentially easier to integrate for basic use cases. The choice between the two depends on the specific requirements of your project and the level of OpenID Connect functionality needed.
OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications
Pros of identity-model-oidc-client-js
- More comprehensive feature set, including support for various OIDC flows and token management
- Better documentation and examples for different use cases
- Active community support and regular updates
Cons of identity-model-oidc-client-js
- Larger bundle size, which may impact performance in some applications
- Steeper learning curve due to more complex API and configuration options
- Less focus on mobile platforms compared to AppAuth-JS
Code Comparison
AppAuth-JS:
const authClient = new AppAuth({
clientId: 'your-client-id',
redirectUri: 'your-redirect-uri',
scope: 'openid profile email'
});
authClient.makeAuthorizationRequest();
identity-model-oidc-client-js:
const oidcClient = new Oidc.UserManager({
authority: 'https://your-authority.com',
client_id: 'your-client-id',
redirect_uri: 'your-redirect-uri',
response_type: 'code',
scope: 'openid profile email'
});
oidcClient.signinRedirect();
The code comparison shows that identity-model-oidc-client-js requires more configuration options but provides more flexibility in handling the authentication flow. AppAuth-JS offers a simpler API for basic authentication scenarios, while identity-model-oidc-client-js allows for more advanced use cases and customization.
Microsoft Authentication Library (MSAL) for JS
Pros of microsoft-authentication-library-for-js
- Specifically designed for Azure AD and Microsoft identity platform
- Extensive documentation and Microsoft support
- Seamless integration with other Microsoft services and APIs
Cons of microsoft-authentication-library-for-js
- Limited to Microsoft identity ecosystem
- May be overly complex for simple authentication scenarios
- Potential vendor lock-in to Microsoft services
Code Comparison
AppAuth-JS:
const authClient = new AppAuth({
clientId: 'your-client-id',
redirectUri: 'your-redirect-uri',
scope: 'openid profile email'
});
authClient.makeAuthorizationRequest();
microsoft-authentication-library-for-js:
const msalConfig = {
auth: {
clientId: 'your-client-id',
authority: 'https://login.microsoftonline.com/your-tenant-id'
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
msalInstance.loginPopup();
Summary
AppAuth-JS is a more generic OpenID Connect library suitable for various identity providers, while microsoft-authentication-library-for-js is tailored for Microsoft's ecosystem. AppAuth-JS offers greater flexibility but may require more setup, whereas microsoft-authentication-library-for-js provides a streamlined experience for Azure AD integration. The choice between the two depends on your specific authentication requirements and whether you're primarily working within the Microsoft ecosystem or need broader identity provider support.
Open Source Identity and Access Management For Modern Applications and Services
Pros of Keycloak
- Comprehensive identity and access management solution with built-in user management, authentication, and authorization features
- Supports multiple protocols (OpenID Connect, SAML, OAuth 2.0) and provides a unified interface for managing various identity providers
- Offers a user-friendly admin console for easy configuration and management
Cons of Keycloak
- Heavier and more complex to set up and maintain compared to AppAuth-JS
- Requires additional server infrastructure and resources to run
- May be overkill for simple authentication scenarios or smaller applications
Code Comparison
AppAuth-JS (OAuth 2.0 Authorization Code flow):
const authorizationRequest = new AuthorizationRequest({
client_id: 'client_id',
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile email',
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
});
Keycloak (JavaScript adapter):
const keycloak = new Keycloak({
url: 'https://keycloak-server/auth',
realm: 'myrealm',
clientId: 'myclient'
});
keycloak.init({ onLoad: 'login-required' });
Both repositories provide authentication solutions, but Keycloak offers a more comprehensive identity management platform, while AppAuth-JS focuses on implementing OAuth 2.0 and OpenID Connect protocols in JavaScript applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
AppAuth for JavaScript is a client SDK for public clients
for communicating with OAuth 2.0
and OpenID Connect providers
following the best practice
RFC 8252 - OAuth 2.0 for Native Apps.
The library is designed for use in Web Apps
, Node.js
CLI applications,
Chrome Apps
and applications that use Electron
or similar frameworks.
It strives to directly map the requests and responses of those specifications, while following the idiomatic style of the implementation language.
The library also supports the PKCE extension to OAuth which was created to secure authorization codes in public clients when custom URI scheme redirects are used. The library is friendly to other extensions (standard or otherwise) with the ability to handle additional parameters in all protocol requests and responses.
Examples
An example application using the library is included in the src/node_app
folder and at https://github.com/googlesamples/appauth-js-electron-sample.
Auth Flow
AppAuth supports manual interaction with the Authorization Server where you need to perform your own token exchanges. This example performs a manual exchange.
Fetch Service Configuration
AuthorizationServiceConfiguration.fetchFromIssuer(openIdConnectUrl)
.then(response => {
log('Fetched service configuration', response);
this.configuration = response;
this.showMessage('Completed fetching configuration');
})
.catch(error => {
log('Something bad happened', error);
this.showMessage(`Something bad happened ${error}`)
});
Make Authorization Requests
this.notifier = new AuthorizationNotifier();
// uses a redirect flow
this.authorizationHandler = new RedirectRequestHandler();
// set notifier to deliver responses
this.authorizationHandler.setAuthorizationNotifier(this.notifier);
// set a listener to listen for authorization responses
this.notifier.setAuthorizationListener((request, response, error) => {
log('Authorization request complete ', request, response, error);
if (response) {
this.code = response.code;
this.showMessage(`Authorization Code ${response.code}`);
}
});
// create a request
let request = new AuthorizationRequest({
client_id: clientId,
redirect_uri: redirectUri,
scope: scope,
response_type: AuthorizationRequest.RESPONSE_TYPE_CODE,
state: undefined,
extras: {'prompt': 'consent', 'access_type': 'offline'}
});
// make the authorization request
this.authorizationHandler.performAuthorizationRequest(this.configuration, request);
Making Token Requests
this.tokenHandler = new BaseTokenRequestHandler();
let request: TokenRequest|null = null;
if (this.code) {
let extras: StringMap|undefined = undefined;
if (this.request && this.request.internal) {
extras = {};
extras['code_verifier'] = this.request.internal['code_verifier'];
}
// use the code to make the token request.
request = new TokenRequest({
client_id: clientId,
redirect_uri: redirectUri,
grant_type: GRANT_TYPE_AUTHORIZATION_CODE,
code: this.code,
refresh_token: undefined,
extras: extras
});
} else if (this.tokenResponse) {
// use the token response to make a request for an access token
request = new TokenRequest({
client_id: clientId,
redirect_uri: redirectUri,
grant_type: GRANT_TYPE_REFRESH_TOKEN,
code: undefined,
refresh_token: this.tokenResponse.refreshToken,
extras: undefined
});
}
this.tokenHandler.performTokenRequest(this.configuration, request)
.then(response => {
// ... do something with token response
});
Development
Preamble
This client has been written with TypeScript.
Setup
-
Install the latest version of Node. NVM (Node Version Manager is highly recommended).
-
Use
nvm install
to install the recommended Node.js version. -
Download the latest version of Visual Studio Code from here.
Provision Dependencies
This app uses npm
to provision it dependencies.
git clone
theAppAuthJS
library and go to the root folder of the project containingpackage.json
file.npm install
to install all the dev and project dependencies.
Thats it! You are now ready to start working on AppAuthJS
.
Development Workflow
The project uses npm
scripts to automate development workflows.
These scripts are made available via the package.json
file.
The following scripts are included:
-
npm run-script compile
ortsc
will compile all your TypeScript files. All compiled files go into thebuilt/
folder. -
npm run-script watch
ortsc --watch
will compile your TypeScript files inwatch
mode. Recommended if you want to get continuous feedback. -
npm run-script build-app
generates the outputbundle.js
file in thebuilt/
directory. This includes the fullAppAuthJS
library including all its dependencies. -
npm test
provisions theKarma
test runner to run all unit tests. All tests are written using Jasmine. To DEBUG your tests, click on theDebug
button in the Karma test runner to look at the actual source of the tests. You can attach break points here. -
npm run-script app
builds the test app on a local web server. This is an end-to-end app which uses AppAuthJS and is a demonstration on how to use the library. -
npm run-script node-app
builds a Node.js CLI sample app. This is an end-to-end app which uses AppAuthJS in a Node.js context.
Top Related Projects
iOS and macOS SDK for communicating with OAuth 2.0 and OpenID Connect providers.
OAuth 2 / OpenID Connect Client API for JavaScript Runtimes
OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications
Microsoft Authentication Library (MSAL) for JS
Open Source Identity and Access Management For Modern Applications and Services
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot