• This repository has been archived on 15/Sep/2022
  • Stars
    star
    1,259
  • Rank 37,354 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated about 2 years ago

Reviews

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

Repository Details

Library to help you work with JWTs on AngularJS

Warning This repository has been archived, the libaray has been deprecated, but remains available on NPM.

angular-jwt

FOSSA Status

This library will help you work with JWTs.

Sponsor

auth0 logo If you want to quickly add secure token-based authentication to your Angular projects, feel free to check Auth0's Angular SDK and free plan at auth0.com/developers

Key Features

  • Decode a JWT from your AngularJS app
  • Check the expiration date of the JWT
  • Automatically send the JWT in every request made to the server
  • Manage the user's authentication state with authManager

Installing it

You have several options: Install with either bower or npm and link to the installed file from html using script tag.

bower install angular-jwt
npm install angular-jwt

jwtHelper

jwtHelper will take care of helping you decode the token and check its expiration date.

Decoding the Token

angular
  .module('app', ['angular-jwt'])
  .controller('Controller', function Controller(jwtHelper) {
    var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8';  

    var tokenPayload = jwtHelper.decodeToken(expToken);
  });

Getting the Token Expiration Date

angular
  .module('app', ['angular-jwt'])
  .controller('Controller', function Controller(jwtHelper) {
    var date = jwtHelper.getTokenExpirationDate(expToken);
  });

Checking if the Token is Expired

angular
  .module('app', ['angular-jwt'])
  .controller('Controller', function Controller(jwtHelper) {
    var bool = jwtHelper.isTokenExpired(expToken);
  });

More Examples

You can see some more examples of how this works in the tests

jwtInterceptor

JWT interceptor will take care of sending the JWT in every request.

Basic Usage

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    // Please note we're annotating the function so that the $injector works when the file is minified
    jwtOptionsProvider.config({
      tokenGetter: ['myService', function(myService) {
        myService.doSomething();
        return localStorage.getItem('id_token');
      }]
    });

    $httpProvider.interceptors.push('jwtInterceptor');
  })
  .controller('Controller', function Controller($http) {
    // If localStorage contains the id_token it will be sent in the request
    // Authorization: Bearer [yourToken] will be sent
    $http({
      url: '/hola',
      method: 'GET'
    });
  });

Configuring the Authentication Scheme

By default, angular-jwt uses the Bearer scheme when sending JSON Web Tokens as an Authorization header. The header that gets attached to $http requests looks like this:

Authorization: Bearer eyJ0eXAiOiJKV...

If you would like to provide your own scheme, you can configure it by setting a value for authPrefix in the jwtOptionsProvider configuration.

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({
      authPrefix: 'MyPrefix '
      ...
    });

    $httpProvider.interceptors.push('jwtInterceptor');

Not Sending the JWT for Specific Requests

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    // Please note we're annotating the function so that the $injector works when the file is minified
    jwtOptionsProvider.config({
      tokenGetter: ['myService', function(myService) {
        myService.doSomething();
        return localStorage.getItem('id_token');
      }]
    });

    $httpProvider.interceptors.push('jwtInterceptor');
  })
  .controller('Controller', function Controller($http) {
    // This request will NOT send the token as it has skipAuthorization
    $http({
      url: '/hola',
      skipAuthorization: true,
      method: 'GET'
    });
  });

Whitelisting Domains

If you are calling an API that is on a domain other than your application's origin, you will need to whitelist it.

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({

      ...

      whiteListedDomains: ['api.myapp.com', 'localhost']
    });
  });

Note that you only need to provide the domain. Protocols (ex: http://) and port numbers should be omitted.

You can also specify the domain using a regular expression.

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({

      ...

      whiteListedDomains: [/^api-version-\d+\.myapp\.com$/i, 'localhost']
    });
  });

Regular expressions should be as strict as possible to prevent attackers from registering their own malicious domains to bypass the whitelist.

Not Sending the JWT for Template Requests

The tokenGetter method can have a parameter options injected by angular-jwt. This parameter is the options object of the current request.

By default the interceptor will send the JWT for all HTTP requests. This includes any ng-include directives or templateUrls defined in a state in the stateProvider. If you want to avoid sending the JWT for these requests you should adapt your tokenGetter method to fit your needs. For example:

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({
      tokenGetter: ['options', function(options) {
        // Skip authentication for any requests ending in .html
        if (options.url.substr(options.url.length - 5) == '.html') {
          return null;
        }

        return localStorage.getItem('id_token');
      }]
    });

    $httpProvider.interceptors.push('jwtInterceptor');
  });

Sending Different Tokens Based on URLs

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({
      tokenGetter: ['options', function(options) {
        if (options.url.indexOf('http://auth0.com') === 0) {
          return localStorage.getItem('auth0.id_token');
        } else {
          return localStorage.getItem('id_token');
        }
      }]
    });
    $httpProvider.interceptors.push('jwtInterceptor');
  })
  .controller('Controller', function Controller($http) {
    // This request will send the auth0.id_token since URL matches
    $http({
      url: 'http://auth0.com/hola',
      skipAuthorization: true,
      method: 'GET'
    });
  });

Managing Authentication state with authManager

Almost all applications that implement authentication need some indication of whether the user is authenticated or not and the authManager service provides a way to do this. Typical cases include conditionally showing and hiding different parts of the UI, checking whether the user is authenticated when the page is refreshed, and restricting routes to authenticated users.

  <button ng-if="!isAuthenticated">Log In</button>
  <button ng-if="isAuthenticated">Log Out</button>

Note: authManager set isAuthenticated on your $rootScope object, If you are using component-based architecture, your component $scope is isolated scope, it does not inherits $rootScope properties, you need to access $rootScope from component's template:

  <button ng-if="!$root.isAuthenticated">Log In</button>
  <button ng-if="$root.isAuthenticated">Log Out</button>

Getting Authentication State on Page Refresh

The authentication state that is set after login will only be good as long as the user doesn't refresh their page. If the page is refreshed, or the browser closed and reopened, the state will be lost. To check whether the user is actually authenticated when the page is refreshed, use the checkAuthOnRefresh method in the application's run block.

angular
  .module('app')
  .run(function(authManager) {

    authManager.checkAuthOnRefresh();

  });

Note: If your tokenGetter relies on request options, be mindful that checkAuthOnRefresh() will pass null as options since the call happens in the run phase of the Angular lifecycle and no requests are fired through the Angular app. If you are using requestion options, check that options isn't null in your tokenGetter function:

...

tokenGetter: ['options', function (options) {
  if (options && options.url.substr(options.url.length - 5) == '.html') {
    return null;
  }
  return localStorage.getItem('id_token');
}],

...

Responding to an Expired Token on Page Refresh

If the user is holding an expired JWT when the page is refreshed, the action that is taken is at your discretion. You may use the tokenHasExpired event to listen for expired tokens on page refresh and respond however you like.

// app.run.js

...

$rootScope.$on('tokenHasExpired', function() {
  alert('Your session has expired!');
});

Limiting Access to Routes

Access to various client-side routes can be limited to users who have an unexpired JWT, which is an indication that they are authenticated. Use requiresLogin: true on whichever routes you want to protect.

...

.state('ping', {
  url: '/ping',
  controller: 'PingController',
  templateUrl: 'components/ping/ping.html',
  controllerAs: 'vm',
  data: {
    requiresLogin: true
  }
});

...

Note: Protecting a route on the client side offers no guarantee that a savvy user won't be able to hack their way to that route. In fact, this could be done simply if the user alters the expiry time in their JWT with a tool like jwt.io. Always ensure that sensitive data is kept off the client side and is protected on the server.

Redirecting the User On Unauthorized Requests

When the user's JWT expires and they attempt a call to a secured endpoint, a 401 - Unauthorized response will be returned. In these cases you will likely want to redirect the user back to the page/state used for authentication so they can log in again. This can be done with the redirectWhenUnauthenticated method in the application's run block.

angular
  .module('app')
  .run(function(authManager) {

    ...

    authManager.redirectWhenUnauthenticated();

  });

Configuring the Login State

The page/state to send the user to when they are redirected because of an unauthorized request can be configured with jwtOptionsProvider.

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({
      unauthenticatedRedirectPath: '/login'
    });
  });

Configuring the Unauthenticated Redirector

If you would like to control the behavior of the redirection that happens when users become unauthenticated, you can configure jwtOptionsProvider with a custom function.

angular
  .module('app', ['angular-jwt'])
  .config(function Config($httpProvider, jwtOptionsProvider) {
    jwtOptionsProvider.config({
      unauthenticatedRedirector: ['$state', function($state) {
        $state.go('app.login');
      }]
    });
  });

Sending the token as a URL Param

angular.module('app', ['angular-jwt'])
.config(function Config($httpProvider, jwtOptionsProvider) {
  jwtOptionsProvider.config({
    urlParam: 'access_token',
    tokenGetter: ['myService', function(myService) {
      myService.doSomething();
      return localStorage.getItem('id_token');
    }]
  });

  $httpProvider.interceptors.push('jwtInterceptor');
})
.controller('Controller', function Controller($http) {
  // If localStorage contains the id_token it will be sent in the request
  // url will contain access_token=[yourToken]
  $http({
    url: '/hola',
    method: 'GET'
  });
})

More examples

You can see some more examples of how this works in the tests

FAQ

I have minification problems with angular-jwt in production. What's going on?

When you're using the tokenGetter function, it's then called with the injector. ngAnnotate doesn't automatically detect that this function receives services as parameters, therefore you must either annotate this method for ngAnnotate to know, or use it like follows:

jwtOptionsProvider({
  tokenGetter: ['store', '$http', function(store, $http) {
    ...
  }]
});

Usages

This library is used in auth0-angular and angular-lock.

Contributing

Just clone the repo, run npm install, bower install and then gulp to work :).

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free account in Auth0

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

FOSSA Status

More Repositories

1

node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
JavaScript
17,054
star
2

java-jwt

Java implementation of JSON Web Token (JWT)
Java
5,403
star
3

express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
TypeScript
4,396
star
4

jwt-decode

Decode JWT tokens; useful for browser applications.
JavaScript
2,913
star
5

angular2-jwt

Helper library for handling JWTs in Angular apps
TypeScript
2,606
star
6

nextjs-auth0

Next.js SDK for signing in with Auth0
TypeScript
2,009
star
7

lock

Auth0's signin solution
JavaScript
1,121
star
8

go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
Go
978
star
9

auth0.js

Auth0 headless browser sdk
JavaScript
949
star
10

auth0-spa-js

Auth0 authentication for Single Page Applications (SPA) with PKCE
TypeScript
900
star
11

auth0-react

Auth0 SDK for React Single Page Applications (SPA)
TypeScript
864
star
12

node-jwks-rsa

A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
JavaScript
824
star
13

node-jws

JSON Web Signatures
JavaScript
698
star
14

angular-storage

A storage library for AngularJS done right
JavaScript
644
star
15

repo-supervisor

Scan your code for security misconfiguration, search for passwords and secrets. 🔍
JavaScript
634
star
16

node-auth0

Node.js client library for the Auth0 platform.
JavaScript
586
star
17

cosmos

🔭 Auth0 Design System
JavaScript
545
star
18

JWTDecode.swift

A JWT decoder for iOS, macOS, tvOS, and watchOS
Swift
545
star
19

nginx-jwt

Lua script for Nginx that performs reverse proxy auth using JWT's
JavaScript
534
star
20

SimpleKeychain

A simple Keychain wrapper for iOS, macOS, tvOS, and watchOS
Swift
488
star
21

react-native-auth0

React Native toolkit for Auth0 API
TypeScript
477
star
22

express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.
JavaScript
464
star
23

auth0-python

Auth0 SDK for Python
Python
445
star
24

JWTDecode.Android

A library to help you decode JWTs for Android
Java
437
star
25

docs

Auth0 documentation
JavaScript
366
star
26

auth0-PHP

PHP SDK for Auth0 Authentication and Management APIs.
PHP
355
star
27

wt-cli

Webtask CLI - all you need is code
JavaScript
322
star
28

auth0.net

.NET client for the Auth0 Authentication & Management APIs.
C#
296
star
29

passport-auth0

Auth0 authentication strategy for Passport.js
JavaScript
283
star
30

rules

Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0
JavaScript
283
star
31

react-native-lock

[DEPRECATED] A wrapper of Lock to use with React Native (iOS & Android)
Java
277
star
32

Auth0.swift

Auth0 SDK for Apple platforms
Swift
275
star
33

auth0-java

Java client library for the Auth0 platform
Java
265
star
34

Lock.swift

A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Swift
251
star
35

auth0-cli

Build, manage and test your Auth0 integrations from the command line
Go
243
star
36

auth0-deploy-cli

The Auth0 Deploy CLI is a tool that helps you manage your Auth0 tenant configuration. It integrates into your development workflows as a standalone CLI or as a node module.
JavaScript
242
star
37

laravel-auth0

Laravel SDK for Auth0 Authentication and Management APIs.
PHP
224
star
38

Auth0.Android

Android toolkit for Auth0 API
Kotlin
213
star
39

jwks-rsa-java

Java
194
star
40

ruby-auth0

Ruby toolkit for Auth0 API
Ruby
189
star
41

cxn

cXn: extensible open-source CDN
Ruby
178
star
42

passport-windowsauth

Windows Authentication strategy for Passport.js
JavaScript
175
star
43

auth0-angular

Auth0 SDK for Angular Single Page Applications
TypeScript
175
star
44

terraform-provider-auth0

The Auth0 Terraform Provider is the official plugin for managing Auth0 tenant configuration through the Terraform tool.
Go
161
star
45

styleguide

🖌 Conjunction of design patterns, components and resources used across our products.
Stylus
160
star
46

jwt-handbook-samples

JWT Handbook code samples
JavaScript
143
star
47

Lock.Android

Android Library to authenticate using Auth0 and with a Native Look & Feel
Java
140
star
48

wordpress

WordPress Plugin for Auth0 Authentication
PHP
133
star
49

node-samlp

SAML Protocol support for node (only IdP for now)
JavaScript
129
star
50

go-auth0

Go SDK for the Auth0 Management API.
Go
122
star
51

passport-linkedin-oauth2

Passport Strategy for LinkedIn OAuth 2.0
JavaScript
115
star
52

omniauth-auth0

OmniAuth strategy to login with Auth0
Ruby
112
star
53

symfony

Symfony SDK for Auth0 Authentication and Management APIs.
PHP
110
star
54

node-odata-parser

OData query string parser for node.js.
JavaScript
106
star
55

node-jwa

JSON Web Algorithms
JavaScript
98
star
56

express-jwt-authz

Validate the JWT scope to authorize access to an endpoint
JavaScript
97
star
57

auth0-vue

Auth0 authentication SDK for Vue.js apps
TypeScript
95
star
58

lock-passwordless

Auth0 Lock Passwordless [DEPRECATED]
JavaScript
93
star
59

auth0-aspnetcore-authentication

SDK for integrating Auth0 in ASPNET Core
C#
93
star
60

node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
TypeScript
88
star
61

open-source-template

A template for open source projects at Auth0
85
star
62

auth0-angular2

84
star
63

auth0-oidc-client-net

OIDC Client for .NET Desktop and Mobile applications
C#
84
star
64

auth0-authorization-extension

Auth0 Extension that adds authorization features to your account
JavaScript
82
star
65

react-browserify-spa-seed

Seed / Boilerplate project to create your own SPA using React, Browserify and ReworkCSS
JavaScript
80
star
66

node-baas

Node.js implementation of Bcrypt as a micro service.
JavaScript
79
star
67

password-sheriff

Password policies made easy.
JavaScript
77
star
68

idtoken-verifier

Lightweight RSA JWT verification
JavaScript
76
star
69

sharelock-android

Sharelock Android app
Java
76
star
70

auth0-spring-security-api

Spring Security integration with Auth0 to secure your API with JWTs
Java
76
star
71

ad-ldap-connector

Auth0 AD and LDAP connector
JavaScript
70
star
72

nodejs-msi

Build an MSI Windows Installer for a node.js application using WIX Toolset.
PowerShell
70
star
73

id-generator

Generates random ids with a prefix (a la Stripe)
JavaScript
66
star
74

node-saml

SAML assertion creation for node
JavaScript
65
star
75

webtask-scripts

JavaScript
61
star
76

TouchIDAuth

A library for passwordless authentication using TouchID & JWT
Objective-C
60
star
77

passport-azure-ad-oauth2

OAuth 2.0 authentication Passport strategies for Windows Azure Active Directory
JavaScript
59
star
78

spa-pkce

JavaScript
58
star
79

discourse-plugin

Discourse plugin to authenticate with auth0.
Ruby
58
star
80

auth0-flutter

Auth0 SDK for Flutter
Dart
58
star
81

auth0-multitenant-spa-api-sample

JQuery SPA + Node.js API with multi-tenant support
JavaScript
58
star
82

sandboxjs

Sandbox node.js code like a boss
JavaScript
58
star
83

multitenant-jwt-auth

This sample shows how to implement an API that authenticates using JWTs. It supports mutiple tenants and JWT blacklisting.
JavaScript
54
star
84

coreos-mongodb

CoreOS MongoDB units
52
star
85

shiny-auth0

Auth0 shiny proxy
JavaScript
51
star
86

auth0-cordova

Auth0 integration for Cordova apps
JavaScript
49
star
87

disyuntor

A circuit-breaker implementation for node.js
TypeScript
48
star
88

sharelock-osx

Swift
47
star
89

passport-wsfed-saml2

passport strategy for both WS-fed and SAML2 protocol
JavaScript
47
star
90

php-jwt-example

Php JWT example.
PHP
46
star
91

auth0-aspnet-owin

Auth0 ASP.NET 4.5 Owin/Katana Authentication Handler
JavaScript
46
star
92

webauthn.me

webauthn.me, learn more about the Web Authentication API or try the debugger.
JavaScript
46
star
93

auth0-dotnet-templates

Auth0 Templates for .NET
C#
44
star
94

auth0-java-mvc-common

Contains common helper classes and api client logic that are used across our Java MVC libraries
Java
43
star
95

auth0-custom-password-reset-hosted-page

An example on how to do a custom reset password hosted page.
HTML
41
star
96

express-oauth2-bearer

Experimental Middleware for express.js to validate access tokens.
JavaScript
40
star
97

magic

Auth0 Cryptography Toolkit
JavaScript
40
star
98

single-page-app-seed

A very opinionated seed for creating Single Page Apps that uses NO framework at all. Just a bunch of component libs
JavaScript
39
star
99

kbd

Styles for <kbd> tags.
HTML
37
star
100

webtask-workshop

36
star