春季启动JWT认证

时间:2017-09-19 08:17:45

标签: java angularjs spring authentication spring-boot

我尝试使用spring boot开发Web应用程序,使用以下教程进行身份验证:http://www.techforumist.com/spring-boot-security-jpa-using-jwt-angularjs-tutorial-2/#comment-2848

它的工作很好但在刷新页面连接丢失(注销)后 - 需要重新登录。 我知道我需要会话/ cookies但我不知道该怎么做。

你可以帮帮我吗? 这是源代码:https://github.com/techforumist/jwt-spring-boot-security-angularjs

thnx

1 个答案:

答案 0 :(得分:0)

您不需要会话/ cookie,因为您使用JWT令牌,其中包含有关用户的信息 在源代码中,我看不到任何代码在浏览器中存储jwt令牌。我也看不到任何刷新jwt。所以我想,你必须实现它(或至少是令牌存储) 这就是我的看法:

  1. 将JWT令牌存储在浏览器内存中。在 https://github.com/techforumist/jwt-spring-boot-security-angularjs/blob/master/src/main/resources/static/app/controllers/login.js你 有res.token值。您可以将此值保存到本地浏览器 存储localStorage.setItem("JwtToken", res.token)
  2. 在您的前端应用中刷新后验证用户。
    要执行此操作,您必须在加载应用时从本地存储中获取令牌,将其设置为所有http请求的默认标头,并向后端的/user端点发出请求,以获取User对象。您可以使用token(使用base64)对用户进行编码,但调用端点会更简单 所以在角度上你可以使用run方法(它在初始化之前完成):

    angular.module('fooApp').run(['$http', '$rootScope', 'AuthService', function($http, $rootScope, AuthService) { var token = localStorage.getItem("JwtToken"); if(token) { $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; $http.get('./user').then(function(resp){ AuthService.user = resp; }); } } ]);

  3. 这应该可以完成页面刷新后的技巧和用户记录 当然下一步应该是jwt令牌刷​​新(在运行/路由更改/每个请求 - 有很多选项),但这是不可能的。