【问题标题】:What is Authentication Interceptor in angular什么是角度的身份验证拦截器
【发布时间】:2016-08-07 02:19:49
【问题描述】:

我有一个 Angular 模板。在 app.js 我有这个配置:

app.config(function ($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');

$routeProvider
.when('/', { .....etc

AuthInterceptor 就是这个工厂:

'use strict';

app.factory('AuthInterceptor', function ($rootScope, $q, $window, $location) {
return {
  request: function (config) {
    config.headers = config.headers || {};
    if ($window.localStorage.token) {
      config.headers.Authorization = 'Token ' + $window.localStorage.token;
    }
    return config;
  },

  responseError: function (response) {
    if (response.status === 401) {
      $window.localStorage.removeItem('token');
      $window.localStorage.removeItem('email');
      $location.path('/');
      return;
    }
    return $q.reject(response);
  }
};
});

它到底是做什么的?

【问题讨论】:

  • 添加包含令牌的授权标头。 Token 存储在 localStorage 中,服务器返回 401 时删除。

标签: angularjs authentication angular-http-interceptors


【解决方案1】:

Angular 中的拦截器,顾名思义,是框架提供的一种简单方法,用于在将应用程序的 http 请求发送到服务器之前对其进行全局拦截和修改。这真的很方便,允许我们配置身份验证令牌、添加请求日志、添加应用程序可能需要的自定义标头等等。

拦截器可以以常规、标准的方式为每个 HTTP 请求/响应执行各种隐式任务,从身份验证到日志记录。如果没有拦截,开发人员将不得不为每个 HttpClient 方法调用显式地实现这些任务。

@Injectable()
    export class RequestLogInterceptor implements HttpInterceptor {
      intercept(
        request: HttpRequest<any>, next: HttpHandler
      ) : Observable<HttpEvent<any>> {
        console.log(request.url);
        return next.handle(request);
      }
    }

intercept 方法将每个请求转换为 Observable,稍后将通过调用 next.handle() 来解决。因此,对于我们的实现来说,它非常简单:您接受请求,记录其 url 并调用 next.handle() 将其发送到服务器而不对其进行任何更改。

【讨论】:

    【解决方案2】:

    “AuthInterceptor”将为之前的每个请求在 headers.Authorization 参数中注入一个 Token。 这将允许您在服务器端保持登录状态,或者检查令牌是否存在并允许一些休息功能。

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 2023-03-22
      • 2015-11-19
      • 2021-01-03
      • 2017-11-16
      • 2021-07-05
      相关资源
      最近更新 更多