npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ng2-jwt

v0.2.0

Published

Helper library for handling JWTs in Angular 2

Downloads

107

Readme

ng2-jwt

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

This is a fork of angular2-jwt and its configured to work with SystemJS without any mappings.

Just include node_modules/ng2-jwt/bundles/ng2-jwt.js script into your project and it should work.

Key Features

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

Installation

npm install ng2-jwt

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 request, you can use the AuthHttp class.

import {AuthHttp, AuthConfig} from 'ng2-jwt';

...

class App {

  thing: string;

  constructor(public authHttp: AuthHttp) {}

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

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(AuthConfig, {
    useFactory: () => {
      return new AuthConfig();
    }
  }),
  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))
  • Supress error and continue with regular HTTP request if no JWT is saved: false

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.

...

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

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

Sending Headers

You may send custom headers with your authHttp request by passing in an options object.

getThing() {
  var myHeader = new Headers();
  myHeader.append('Content-Type', 'application/json');

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

  // Pass it after the body in a POST request
  this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader} )
    .subscribe(
      data => this.thing = data,
      err => console.log(error),
      () => console.log('Request Complete')
    );
}

Using the Observable Token Stream

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

...

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.


...

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.


...

@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.

Contributing

Pull requests are welcome!

Development

Use npm run dev to compile and watch for changes.

License

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