【个人笔记重点,不作为参考】主题:angular2-jwt

来源:互联网 发布:智能时代的数据化企业 编辑:程序博客网 时间:2024/06/06 01:29

环境:angular2

import { provideAuth } from 'angular2-jwt';@NgModule({    providers: [     provideAuth({      headerName: 'Access-Token',      /* headerPrefix: "YOUR_HEADER_PREFIX",*/      tokenName: 'DR-Access-Token',      tokenGetter: (() => window.localStorage.getItem('DR-Access-Token')),      globalHeaders: [{'Content-Type': 'application/json'}],      noJwtError: false,      noTokenScheme: false    }),  ],  bootstrap: [ AppComponent ]})export class AppModule { }


原理:登录时请求后台,返回给你一个标识,并且放于localstorage。验证你的localstorage(本地存储)里面有没有DR-Accss-Token(标识)。如果没有将不能跳转任何路由。当然这个




What is this Library for?

这个库干嘛的?

angular2-jwt is a small and unopinionated library that is useful for automatically attaching a JSON Web Token (JWT) as an Authorization header when making HTTP requests from an Angular 2 app. It also has a number of helper methods that are useful for doing things like decoding JWTs.

angular2-jwt是轻量的且unopinionated的库,当从Angular 2 app中产生了HTTP requests,作为授权的header用于自动匹配JSON Web Token (JWT)。他也有多个友好的方法,如:decoding JWTs

This library does not have any functionality for (or opinion about) implementing user authentication and retrieving JWTs to begin with. Those details will vary depending on your setup, but in most cases, you will use a regular HTTP request to authenticate your users and then save their JWTs in local storage or in a cookie if successful.

起初这个库没有任何功能,对于填写用户认证和 检索(储存的信息)JWTs。那些信息将会使你的依赖在设置中不同,但大多数成功例子,会使用regular HTTP request 来认证你的用户,然后保存他们的JWTs 在 local storage(本地存储) 或者 cookie(缓存)

For more on implementing authentication endpoints, see this tutorial for an example using HapiJS.

渴望执行认证终点,看教程,如使用HapiJS

Key Features

主要功能
  • Send a JWT on a per-request basis using the explicit AuthHttp class
    使JWT基于明确的AuthHttp类参加 每个request(请求)
  • Decode a JWT from your Angular 2 app.
    从你的Angular 2 app 中Decode(解码)JWT
  • Check the expiration date of the JWT
    检查JWT的有限期
  • Conditionally allow route navigation based on JWT status
    有条件的允许,路由导航基于JWT状态

Installation

安装
npm install angular2-jwt

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

这个库包含多个angular 2 apps中有用的助手

  1. AuthHttp - allows for individual and explicit authenticated HTTP requests
    AuthHttp 允许个人且明确的验证HTTP requests(请求)

  2. tokenNotExpired - 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
    tokenNotExpired 允许你检查local storage(本地存储)有无过期JWT(JSON Web Tocken)。如果没认证,有利于 (显示/隐藏 元素与阻止导航至某一路由

Using AUTH_PROVIDERS
使用 AUTH_PRIVIDERS

Add AUTH_PROVIDERS to the providers array in your @NgModule.
从你的@NgModule中的providers添加AUTH_PROVIDERS

import { NgModule } from '@angular/core';import { AUTH_PROVIDERS } from 'angular2-jwt';...@NgModule({  ...  providers: [    AUTH_PROVIDERS  ],  ...})

Sending Authenticated Requests
发送身份验证请求

If you wish to only send a JWT on a specific HTTP request, you can use the AuthHttp class. This class is a wrapper for Angular 2's Http and thus supports all the same HTTP methods.
如果你仅希望派JWT参加{ 明确的 }HTTP请求,可以使用AuthHttp类。该类包装了Angular 2的Http且支持所有相同的HTTP方法。

import { AuthHttp } from 'angular2-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(err),        () => console.log('Request Complete')      );  }}

Configuration Options
配置项

AUTH_PROVIDERS gives a default configuration setup:
AUTH_PROVIDERS提供默认配置:

  • 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
  • Global Headers: none

If you wish to configure the headerNameheaderPrefixtokenNametokenGetterfunction, noTokenSchemeglobalHeaders, or noJwtError boolean, you can using provideAuth or the factory pattern (see below).

如果想配置
headerNameheaderPrefixtokenNametokenGetterfunction, noTokenSchemeglobalHeaders, or noJwtError boolean,可以使用privideAuth或者工厂模式(看下面)

Errors

By default, if there is no valid JWT saved, AuthHttp will return an Observable error with 'Invalid JWT'. If you would like to continue with an unauthenticated request instead, you can set noJwtError to true.
默认情况下,如果无有意义的JWT被保存,AuthHttp会用‘Invalid JWT’返回一个Observable error(这里的Observable指观察者模式)。如果你想继续用无认证的request(请求)代替,你能设置 noJwtError为 true。

Token Scheme

The default scheme for the Authorization header is Bearer, but you may either provide your own by specifying a headerPrefix, or you may remove the prefix altogether by setting noTokenScheme to true.
用户认证的header默认体系是Bearer,但是你可以在以下两种选一个。1、指定一个headerPrefix。2、移除prefix。设置noTokenScheme 为 true

Global Headers

You may set as many global headers as you like by passing an array of header-shaped objects to globalHeaders.
你可以指定配置许多的global headers,制定成一个header-shaped(合适的header)对象的数组。放置到globalHeaders中。

Configuring angular2-jwt with provideAuth
使用privideAuth配置angular2-jwt

You may customize any of the above options using provideAuth in the providersarray in your @NgModule.
你可以在@NgModule的providers数组中privideAuth定制上面的任何配置

import { NgModule } from '@angular/core';import { provideAuth } from 'angular2-jwt';...@NgModule({  ...  providers: [    provideAuth({      headerName: YOUR_HEADER_NAME,      headerPrefix: YOUR_HEADER_PREFIX,      tokenName: YOUR_TOKEN_NAME,      tokenGetter: YOUR_TOKEN_GETTER_FUNCTION,      globalHeaders: [{'Content-Type':'application/json'}],      noJwtError: true,      noTokenScheme: true    })  ],  ...})

Configuation for Ionic 2

To configure angular2-jwt in Ionic 2 applications, use the factory pattern in your @NgModule. Since Ionic 2 provides its own API for accessing local storage, configure the tokenGetter to use it.

import { AuthHttp, AuthConfig } from 'angular2-jwt';import { Http } from '@angular/http';import { Storage } from '@ionic/storage';let storage = new Storage();export function getAuthHttp(http) {  return new AuthHttp(new AuthConfig({    headerPrefix: YOUR_HEADER_PREFIX,    noJwtError: true,    globalHeaders: [{'Accept': 'application/json'}],    tokenGetter: (() => storage.get('id_token')),  }), http);}@NgModule({  imports: [    IonicModule.forRoot(MyApp),  ],  providers: [    {      provide: AuthHttp,      useFactory: getAuthHttp,      deps: [Http]    },  ...  bootstrap: [IonicApp],  ...})

To use tokenNotExpired with Ionic 2, use the Storage class directly in the function.

import { Storage } from '@ionic/storage';import { tokenNotExpired } from 'angular2-jwt';let storage = new Storage();this.storage.get('id_token').then(token => {    console.log(tokenNotExpired(null, token)); // Returns true/false});

Sending Per-Request Headers
发送每个请求headers

You may also send custom headers on a per-request basis with your authHttprequest by passing them in an options object.
你也可以发送定制headers类型在每个请求中(基于你的authHttp请求,绕过配置对象)。

getThing() {  let 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
使用Observable Token Stream(可观察标识序列)

If you wish to use the JWT as an observable stream, you can call tokenStreamfrom AuthHttp.
如果你希望使用JWT作为观察序列,你能使用AuthHttp中的tokenStream方法

...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 observable streams. The tokenStream can be mapped and combined with other streams at will.
对于你想在哪里产生HTTP请求到observable steams外,是有用的。tokenStream能被映射且与其他任意steams结合

Using JwtHelper in Components
在组件使用JwtHelper

The JwtHelper class has several useful methods that can be utilized in your components:
JwtHelper类有多个好用的方法,能利用你的组件:

  • decodeToken
  • getTokenExpirationDate
  • isTokenExpired

You can use these methods by passing in the token to be evaluated.
你能使用这些方法,通过被评估的token

...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 Authentication 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.
tokenNotExpired 函数用于检查 JWT 是否存在于 local storage中,如果存在,他是否访问过期。如果token有效返回true,否则返回false

Note: tokenNotExpired will by default assume the token name is id_tokenunless a token name is passed to it, ex: tokenNotExpired('token_name'). This will be changed in a future release to automatically use the token name that is set in AuthConfig.
注释:tokenNotExpired将由默认呈现token name是id_token,,除非token name由:tokenNotExpired('token_name')。在AuthConfig中创建使用token name,会使将来的发行被改变

// auth.service.tsimport { tokenNotExpired } from 'angular2-jwt';...loggedIn() {  return tokenNotExpired();}...

The loggedIn method can now be used in views to conditionally hide and show elements.
loggedIn方法用views来有条件的隐藏与显示元素。

 <button id="login" *ngIf="!auth.loggedIn()">Log In</button> <button id="logout" *ngIf="auth.loggedIn()">Log Out</button>

To guard routes that should be limited to authenticated users, set up an AuthGuard.
路由守卫用于限制鉴定用户,创建AuthGuard

// auth-guard.service.tsimport { Injectable } from '@angular/core';import { Router } from '@angular/router';import { CanActivate } from '@angular/router';import { Auth } from './auth.service';@Injectable()export class AuthGuard implements CanActivate {  constructor(private auth: Auth, private router: Router) {}  canActivate() {    if(this.auth.loggedIn()) {      return true;    } else {      this.router.navigate(['unauthorized']);      return false;    }  }}

With the guard in place, you can use it in your route configuration.

...import { AuthGuard } from './auth.guard';export const routes: RouterConfig = [  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] },  { path: 'unauthorized', component: UnauthorizedComponent }];...

Contributing

Pull requests are welcome!

Development

Use npm run dev to compile and watch for changes.

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, among 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 identitysecurely.
  • 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.

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.

Author

Auth0

License

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

阅读全文
0 0
原创粉丝点击