简体   繁体   中英

Spring boot JWT auth

i try to develop web app using spring boot , for authentication im using following tutorial : http://www.techforumist.com/spring-boot-security-jpa-using-jwt-angularjs-tutorial-2/#comment-2848

its works nice but after refresh page connection Loss(Log out) - and need re login . i know i need session / cookies but i don't know how to do this .

can you Help me ? here is source code : https://github.com/techforumist/jwt-spring-boot-security-angularjs

thnx

You don't need session/cookies, because you use JWT token, which contains information about the user.
In source code, I can't see any code to store jwt token in browser. I can't see any refresh jwt as well. So I guess, you have to implement that (or at least token store).
This is how I see it:

  1. Store JWT token in browser memory. In https://github.com/techforumist/jwt-spring-boot-security-angularjs/blob/master/src/main/resources/static/app/controllers/login.js you have res.token value. You can save this value to browser local storage with localStorage.setItem("JwtToken", res.token) .
  2. Authenticate user after refresh in your frontend app.
    To do this, you have to grab the token from local storage when app is loading, set it as default header to all http requests and make request to /user endpoint in your backend, to get User object. You can encode user from token (with base64), but calling endpoint will be simpler.
    So on angular you can use run method (it's done before initialization):

    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; }); } } ]);

This should do what the trick and user will be logged after page refresh.
Of course the next step should be jwt token refresh (on run/route change/every request - there are many options), but that is beyond the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM