When the login is successful, return to a authentication request header, the next time the user request, only need to attach the request header, you can directly access the resources.
Pom.xml
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactid>jjwt</ Artifactid> <version>0.7.0</version></dependency>
Write a filter
@Component @slf4j Public classJwtauthenticationtokenfilterextendsOnceperrequestfilter {Private Static FinalString Application_json = "Application/json;charset=utf-8"; @AutowiredPrivateUserdetailsservice Userdetailsservice; @AutowiredPrivateJwttokenutil Jwttokenutil; @AutowiredPrivatejwtproperties jwtproperties; @Overrideprotected voidDofilterinternal (HttpServletRequest request, httpservletresponse response, Filterchain chain)throwsservletexception, IOException {String AuthToken=Request.getheader (Jwtproperties.getheader ()); if(!Stringutils.isempty (AuthToken)) {Jwttoken Jwttoken; Try{Jwttoken=Jwttokenutil.getjwttoken (AuthToken); String username=Jwttoken.getusername (); if(Username! =NULL&& Securitycontextholder.getcontext (). getauthentication () = =NULL) {userdetails userdetails=Userdetailsservice.loaduserbyusername (username); if(Jwttokenutil.validatetoken (AuthToken, userdetails)) {Usernamepasswordauthenticationtoken aut Hentication=NewUsernamepasswordauthenticationtoken (Userdetails,NULL, Userdetails.getauthorities ()); Authentication.setdetails (NewWebauthenticationdetailssource (). Builddetails (request)); Securitycontextholder.getcontext (). Setauthentication (authentication); Log.info ("Authentication passed: {}", username); } } } Catch(invalidjwttokenexception invalidjwttokenexception) {response.setcontenttype (Application_json); Log.error (invalidjwttokenexception.invalid_jwt_token_exception); Resultvo<String> Resultvo =NewResultvo<>(); Resultvo.setsuccess (false); Resultvo.setmsg (invalidjwttokenexception.invalid_jwt_token_exception); PrintWriter writer=Response.getwriter (); Writer.write (json.tojsonstring (Resultvo)); Writer.close (); return; }} chain.dofilter (request, response); }}
Then add in the Config class
@Override protected void throws Exception {http.addfilterbefore (Jwtauthenticationtokenfilter, Usernamepasswordauthenticationfilter. class );}
Spring Security JWT