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

angular2-jwt

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

angular2-jwt

Helper library for handling JWTs in Angular 2

  • 0.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3.8K
decreased by-5.73%
Maintainers
1
Weekly downloads
 
Created
Source

angular2-jwt

angular2-jwt is a helper library for working with JWTs in your Angular 2 applications.

Key Features

  • Decode a JWT from your Angular 2 app
  • Check the expiration date of the JWT
  • Send a JWT on a per-request basis using the explicit AuthHttp class

Installation

npm install

The library comes with several helpers that are useful in your Angular 2 apps.

  1. AuthHttp - allows for individual and explicit authenticated HTTP requests
  2. AuthStatus - allows you to check whether there is a non-expired JWT in local storage. This can be used for conditionally showing/hiding elements and stopping navigation to certain routes if the user isn't authenticated

Sending Authenticated Requests

If you wish to only send a JWT on a specific HTTP requests, you can use the AuthHttp class.

// app.ts

import {Component, View, bootstrap, provide} from 'angular2/angular2';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {AuthHttp} from 'angular2-jwt/angular2-jwt';

...

class App {
  
  thing: string;

  constructor(public authHttp:AuthHttp) {}

  getThing() {
    this.authHttp.get('http://example.com/api/thing')
      .map(res => res.json())
      .subscribe(
        data => this.thing = data,
        err => console.log(error),
        () => console.log('Request Complete')
      );
  }
}

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(AuthHttp, { useFactory: () => {
    return new AuthHttp()
  }})
])

A default configuration for header and token details is provided:

  • Header Name: Authorization
  • Header Prefix: Bearer
  • Token Name: id_token
  • Token Getter Function: (() => localStorage.getItem(tokenName))
  • Error thrown if no JWT is saved: true

If you wish to configure the headerName, headerPrefix, tokenName, tokenGetter function, or noJwtError boolean, you can pass a config object when AuthHttp is injected.

By default, if there is no valid JWT saved, AuthHttp will throw an 'Invalid JWT' error. If you would like to continue with an unauthenticated request instead, you can set noJwtError to true.

// app.ts

...

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(AuthHttp, { useFactory: () => {
    return new AuthHttp({
      headerName: YOUR_HEADER_NAME,
      headerPrefix: YOUR_HEADER_PREFIX,
      tokenName: YOUR_TOKEN_NAME,
      tokenGetter: YOUR_TOKEN_GETTER_FUNCTION,
      noJwtError: true 
    })
  }})
])

The AuthHttp class supports all the same HTTP verbs as Angular 2's Http.

Using the Observable Token Stream

If you wish to use the JWT as an observable stream, you can call tokenStream from AuthHttp.

// app.ts

tokenSubscription() {
  this.authHttp.tokenStream.subscribe(
      data => console.log(data),
      err => console.log(err),
      () => console.log('Complete')
    );
}

This can be useful for cases where you want to make HTTP requests out of obsevable streams. The tokenStream can be mapped and combined with other streams at will.

Using JwtHelper in Components

The JwtHelper class has several useful methods that can be utilized in your components:

  • decodeToken
  • getTokenExpirationDate
  • isTokenExpired

You can use these methods by passing in the token to be evaluated.

// app.ts

...

jwtHelper: JwtHelper = new JwtHelper();

...

useJwtHelper() {
  var token = localStorage.getItem('id_token');
  
  console.log(
    this.jwtHelper.decodeToken(token),
    this.jwtHelper.getTokenExpirationDate(token),
    this.jwtHelper.isTokenExpired(token)
  );
}

...

Checking Login to Hide/Show Elements and Handle Routing

The tokenNotExpired function can be used to check whether a JWT exists in local storage, and if it does, whether it has expired or not. If the token is valid, tokenNotExpired returns true, otherwise it returns false.

The router's @CanActivate lifecycle hook can be used with tokenNotExpired to determine if a route should be accessible. This lifecycle hook is run before the component class instantiates. If @CanActivate receives true, the router will allow navigation, and if it receives false, it won't.

// app.ts

...

import {Component, View, bootstrap, provide} from 'angular2/http';
import {tokenNotExpired} from 'angular2-jwt/angular2-jwt';
import {RouteConfig, RouteParams, ROUTER_DIRECTIVES, APP_BASE_HREF, ROUTER_PROVIDERS, CanActivate} from 'angular2/router'

@Component({
  selector: 'secret-route'
})

@View({
  template: `<h1>If you see this, you have a JWT</h1>`
})

@CanActivate(() => tokenNotExpired())

class SecretRoute {}

You can pass a different tokenName for @CanActivate to use as the first argument to the function. If you wish to define your own function for tokenNotExpired to use, pass null first and then the function.

Development

To extend or contribute to this library, first clone the repo. A gulp task is set up for transpiling the TypeScript file to ES5. Just run gulp and changes will be watched.

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.

Keywords

FAQs

Package last updated on 09 Nov 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