当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

angular-jwt

Library to help you work with JWTs on AngularJS
授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 糜单弓
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

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 ortemplateUrls defined in a state in the stateProvider. If you want to avoid sending the JWT for these requests youshould 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

  • 版本说明: @ auth0 / angular-jwt v2将与Angular v6 +和RxJS v6 +一起使用。对于Angular v4.3到v5 +,请使用@ auth0 / angular-jwt v1 区别于session验证: session:认证中,每个用户都要生成一份session,这份session通常保存在内存中,随着用户量的增加,服务端的开销会增大,而且对分布式应用不是很友

  • 我需要在 https://github.com/auth0/angular2-jwt/tree/v1.0 JWT Interceptor中使用基于角色的身份验证方面的建议 . 如何使用Angular 5执行"admin"角色身份验证? 现在我有:登录服务器发送回有效负载中的用户ID并使用canActivate的jwt令牌后,我的应用程序检查令牌是否存在然后允许进入安全站点 . @Injectabl

  • 版本说明: @ auth0 / angular-jwt v2将与Angular v6 +和RxJS v6 +一起使用。对于Angular v4.3到v5 +,请使用@ auth0 / angular-jwt v1 区别于session验证: session:认证中,每个用户都要生成一份session,这份session通常保存在内存中,随着用户量的增加,服务端的开销会增大,而且对分布式应用不是很友

  • Angular之jwt令牌身份验证 demo https://gitee.com/powersky/jwt 介绍 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,

 相关资料
  • Angular 是一款十分流行且好用的 Web 前端框架,目前由 Google 维护。这个条目收录的是 Angular 2 及其后面的版本。由于官方已将 Angular 2 和之前的版本 Angular.js 分开维护(两者的 GitHub 地址和项目主页皆不相同),所以就有了这个页面。传送门:Angular.js 特性 跨平台 渐进式 Web 应用 借助现代化 Web 平台的力量,交付 app

  • 即将到来的Angular 2框架是使用TypeScript开发的。 因此Angular和TypeScript一起使用非常简单方便。 Angular团队也在其文档里把TypeScript视为一等公民。 正因为这样,你总是可以在Angular 2官网(或Angular 2官网中文版)里查看到最新的结合使用Angular和TypeScript的参考文档。 在这里查看快速上手指南,现在就开始学习吧!

  • 从头开始创建项目 lint你的代码 运行您的单元测试和端到端测试。 Angular 2 CLI目前只在TypeScript中生成框架,稍后还会有其他版本。

  • 这小节内容是译者加的,因为我认为对于新手而言,学习一个框架是有成本的,特别是对于一个不算简单的技术来说,我希望这篇教程是对新手友好的,所以我首先要让你放心的将时间和精力投入到Angular2 中。那我们先不谈技术细节,先用数据说话。 这里我多说一句,最近看一些文章中谷歌趋势截图,大都没有把范围限定在“编程”上。图中可以看出Vue2非常少,所以在下面比较中不再单独统计。 教程数量 这里我选取的主要是

  • 我们已经在Highcharts Configuration Syntax一章中看到了用于绘制图表的配置 。 下面给出角度计图表的示例。 配置 (Configurations) 现在让我们看一下所采取的其他配置/步骤。 chart.type 将图表类型配置为基于计量。 将类型设置为“规格”。 var chart = { type: 'guage' }; pane 此类型仅适用于极坐标图和角度

  • 角度计图表用于绘制仪表/仪表类型图表。 在本节中,我们将讨论不同类型的角度计图表。 Sr.No. 图表类型和描述 1 角度计 角度表。 2 实心仪​​表 实心图表。 3 Clock 时钟。 4 带双轴的仪表 带双轴的仪表图。 5 VU表 VU表图表。

  • Highcharts Angular 是我们基于 Angular 框架封装的 Highcharts,可以很方便的在 Angular 开发环境中使用 Highcharts 创建交互性图表。 开发环境 确保您的 node, NPM, Angular 已经更新到最新版本。以下是经过测试和要求的版本: node 6.10.2+ npm 4.6.1+ @angular/cli 6.0.0+ Highchar

  • Angular Kickstart 是基于 AngularJS,GulpJS 和 Bower 的完整可伸缩构建系统,能加快 AngularJS 应用的开发。开发者只需关注代码的编写和测试,剩下的工作 AngularJS Kickstart 会帮忙完成。 特性: 5 个简单的任务:gulp serve,gulp serve:dist, gulp serve:tdd, gulp test:unit,