【问题标题】:AngularJS Remember me functionality using JWT AuthAngularJS 使用 JWT Auth 记住我的功能
【发布时间】:2016-06-23 18:12:50
【问题描述】:

我使用 Angular JS 开发了一个 Spring Web 应用程序。对于当前项目,客户端身份验证使用 Cookie。 在学习了JWTs的优势之后, 我使用 JWTs(Json Web Token) 重写了应用程序身份验证。

我关心的是如何在不使用 Cookie 功能或 Laravel 支持的情况下在 AngularJS 中使用 JWT 处理 “记住我”功能

如果你们中的任何专家可以分享我的建议或示例代码。这真的很有帮助。我尝试在互联网上搜索,但未能获得可参考的示例实现。

谢谢。

【问题讨论】:

  • 您可以将令牌存储在 localStorage 中
  • 如果你可以分享一些示例代码。会很有帮助的。
  • localStorage.setItem("jwt", angular.toJson(yourToken));

标签: angularjs


【解决方案1】:

在客户端存储 JWT 的选项之一可能是 window.localStorage,它存储没有过期日期的数据。 之后,对于每个$http 请求(在身份验证标头中),您使用拦截器将此令牌发送到服务器,如下所示,

angular.module('myApp').factory('authInterceptor', ['$q', function ($q) {
        return {
            request: function (config) {
                config.headers = config.headers || {};
                if (config.headers.skipAuthorization === false) {
                    var token = localStorage.getItem('authenticationToken');
                    if (token != null) {

                        config.headers.Authorization = token;
                    }
                }
                return config;
            },
            response: function (response) {
                if (response.headers("Authorization") != undefined || response.headers("Authorization") != '') {
                    localStorage.setItem('authenticationToken', response.headers("Authorization"));
                }
                return response;
            },
            responseError: function (rejection) {
                if (rejection.status === "401") {
                    localStorage.removeItem('authenticationToken');
                }
                return $q.reject(rejection);
            }
        };
    } ]);

    angular.module('myApp').config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('authInterceptor');
    } ]);

对于您希望将此令牌发送到服务器的每个请求,将标头中的skipAuthorization:false 设置为,

$http({
....
headers:{skipAuthorization:false}
}).then(....)

【讨论】:

  • 但是JWT 本身就有过期时间。我们可以将令牌存储在localStorage,但是当我们发送到服务器时,JWT 会检查过期时间。有什么想法吗?
  • 是的,在服务器上,当我们解码JWT并验证它时,它会在token过期时报错
猜你喜欢
  • 2019-02-16
  • 2017-08-10
  • 2021-06-25
  • 2014-12-26
  • 1970-01-01
  • 2012-09-08
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多