【问题标题】:Redirecting to another page with JWT auth header in angularjs在angularjs中使用JWT auth标头重定向到另一个页面
【发布时间】:2018-03-03 01:16:39
【问题描述】:

我有一个两个模块的 angularjs 应用程序。一个模块处理身份验证(登录、注册),第二个模块是“聊天”,它在 nodejs 后端使用 passport-jwt 策略受到保护。两个模块都有单独的index.html 文件。 身份验证模块在注册控制器中有一个register() 方法,如下所示:

$scope.register = function () {

         $http({
            method: 'post',
            url: '/api/register',
            data: {
                username: $scope.username,
                email: $scope.email,
                password: $scope.password
            },
            headers: {
                'Content-Type': 'application/json'
            }
        })

/api/register 路由执行所有与注册相关的操作)和登录控制器中的 login() 方法如下所示:

 $scope.login = function () {
            $http({
                method: 'post',
                url: '/api/login',
                data: {
                    username: $scope.username,
                    password: $scope.password
                },
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function success(res) {
                //TODO redirection to '/chat' with auth token
            }
        };

如果用户在数据库中,则 api 会发回一个 jwt 令牌,该令牌在 res.body.token 上可用,并且应该使用该令牌获取一个安全的聊天页面,该页面可在“localhost:3000/chat”网址上使用。问题是我不知道如何使用包含令牌的 Authorization 标头从角度客户端发送正确的请求以获取该聊天页面。

【问题讨论】:

  • 将令牌保存到本地存储或 cookie,然后重定向到聊天。然后在聊天控制器或组件构造函数中获取令牌并验证它。如果无效,则重定向到身份验证。如果有效则加载页面。

标签: javascript angularjs http jwt passport.js


【解决方案1】:

您可以使用 HTTP 拦截器,它将在请求标头中添加 Bearer 令牌-

// Injects an HTTP interceptor that replaces a "Bearer" authorization header with the current Bearer token.
module.factory('oauthHttpInterceptor', function (OAuth) {
  return {
    request: function (config) {      
      if (config.headers.Authorization === 'Bearer') {
        config.headers.Authorization = 'Bearer ' + btoa(OAuth.accessToken);
      }
      return config;
    }
  };
});

module.config(function ($httpProvider) {
  $httpProvider.interceptors.push('oauthHttpInterceptor');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2021-06-27
    • 2012-09-26
    相关资源
    最近更新 更多