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

ng-jwt

v1.1.11

Published

Provides an angular2 auth module to handle authentication based on JWT

Downloads

59

Readme

ng-jwt

NPM

Provides an Angular (2-5) auth module to handle authentication based on JWT.

tnx angular-jwt

Feature status:

| Feature | Status | Docs | |------------------|-------------------------------------|--------------| | AuthenticationService | Available | README | | TokenService | Available | README | | AuthHttp | Available | README | | Auth | Available | README | | LoggedInAuth | Available | README | | LoggedOutAuth | Available | README |

Installation

ng-jwt is available on NPM

$ npm install ng-jwt --save

Setup & Usage

Once the module has been installed, you need to include NgJwtModule into your root module:

import { NgJwtModule } from 'ng-jwt';
...
@NgModule({
  imports: [
    ...
    NgJwtModule.forRoot({
        loginEndPoint: 'http://localhost:5000/connect/token',
        loginParams: {"grant_type": "password", "client_id": "roclient.public"}
    }),
    ...
  ],
  ...
})
export class AppModule {}

In the forRoot function you can specify a custom config as well.

Feature status:

| Feature | Desc |Default | |------------------|-------------------------------------|--------------| | loginEndPoint * | Endpoint url for login with AuthenticationService | [null / Require] | | loginTokenName | Token object name for reading from result | access_token | | loginParams | additional params for sending login request | [null / optional] | | headerName | set Authorization header name for AuthHttp Requests | Authorization | | headerPrefix | Authorization value for AuthHttp Requests | Bearer | | guards | Logged[in/out] guard redirect router name | [null] |

Login && Logout

AuthenticationService service comes withlogout and login function built-in:

import {Component} from '@angular/core';
import {Auth, AuthenticationService} from "ng-jwt";

@Component({
	...
})
export class AppComponent {

	constructor(private authentication: AuthenticationService) {
	}

	logOut() {
		this.authentication.logout();
	}

	login() {
		this.authentication.login('admin', '123456').subscribe(data => console.log((data ? "Success" : "Failed")), error => console.log(error));
	}
}

Manually Login & Logout

In case of of needing a customized Login/Logout functionality, you may use TokenService.

import {Component} from '@angular/core';
import {TokenService} from "ng-jwt";
import {Http} from "@angular/http";

@Component({
...
})
export class AppComponent {

	constructor(private _http: Http, private _tokenService: TokenService) {
	}

	logOut() {
		this._tokenService.removeToken();
	}

	login(username: string, pass: string) {
		this._http.post('/token', {
			username: username,
			password: pass
		}).map(res => res.json())
			.subscribe(response => this._tokenService.setToken(response.token), error => console.error(error));
	}
}

Sending Requests

ng-jwt uses HttpInterceptor to modify HttpClient headers for Authentication. So while using HttpClientModule, ng-jwt would send the Authentication headers alongside the request.

for angular < 4.3:

If you want to send a request with the Authorization header set with the JWT token you can use the AuthHttp class. It will set the authentication headers on the request on the fly.

import { AuthHttp } from 'ng-jwt';
...
@Component({
  ...
})
export class AppComponent {
  constructor(private _authHttp: AuthHttp) {}

  getThing() {
    this._authHttp.get('/get/thing') .subscribe(
        data => this.thing = data,
        error => console.error(error),
        () => console.log('finish ...')
    )
  }
}

Login Validation

Auth class provides another helper method for authentication validation. By using Auth.loggedIn function you can check if the client is logged in. This method returns a Boolean.

import {Component, OnInit} from '@angular/core';
import {Auth} from "ng-jwt";

@Component({
...
})
export class AppComponent implements OnInit {
	constructor(public _auth: Auth) {
	}

	ngOnInit(): void {
		console.log(this._auth.loggedIn());
	}
}

Default Auth Guards

If you want to loggedIn in router:

for authModule config:

import { AuthModule } from 'ng-jwt';
...
@NgModule({
  imports: [
    ...
    AuthModule.forRoot({
        loginEndPoint: 'http://localhost:5000/connect/token',
        loginParams: {"grant_type": "password", "client_id": "roclient.public"},
        guards: {loggedInGuard: {redirectUrl: 'unauthorized'}, loggedOutGuard: {redirectUrl: ''}}
    }),
    ...
  ],
  ...
})
export class AppModule {}

for route config:

const routes: Routes = [
	{path: 'family', component: FamilyListComponent, canActivate: [LoggedInAuth]},
	{path: 'unauthorized', component: UnAuthorizedComponent}
];

License

ng-jwt is released under MIT license.

Author

Mo3in