1. Introduction of JWT Dependency
<!--The introduction of JWT dependency, because it is based on Java, so need is JAVA-JWT - <Dependency> <groupId>Io.jsonwebtoken</groupId> <Artifactid>Jjwt</Artifactid> <version>0.9.1</version> </Dependency> <Dependency> <groupId>Com.auth0</groupId> <Artifactid>Java-jwt</Artifactid> <version>3.4.0</version> </Dependency>
2. Create two annotations, Passtoken and Userlogintoken, used in project development, if you need permission validation to label Userlogintoken, if access to a resource does not require permission verification then normal writing does not require any annotations, if a request is logged in operation, Add Passtoken annotations to the method on which the user is logged on.
Passtoken Packagecom.pjb.springbootjjwt.annotation;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/** * @authorJinbin * @date 2018-07-08 20:38*/@Target ({elementtype.method, elementtype.type}) @Retention (retentionpolicy.runtime) Public@InterfacePasstoken {BooleanRequired ()default true;}
Userlogintoken Packagecom.pjb.springbootjjwt.annotation;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/** * @authorJinbin * @date 2018-07-08 20:40*/@Target ({elementtype.method, elementtype.type}) @Retention (retentionpolicy.runtime) Public@InterfaceUserlogintoken {BooleanRequired ()default true;}
Annotation Resolution: From the above we have newly created two classes we can see the main and so on four points to learn the first: How to create an annotation second: add @target annotations on our custom annotations (annotation explanation: Whether the annotation we define can work on a class or a method or a property) Third: New on our custom annotations @Retention Annotations (Annotation interpretation: The role is to define how long the annotations it notes retain, a total of three strategies, the SOURCE is ignored by the compiler, class annotations will be retained in the class file, but will not be retained by the VM at run time. This is the default behavior, and all annotations that are not annotated with retention will take this strategy. Runtime is reserved to run time. So we can get the annotation information by reflection. Four: Boolean required () default true; The default required () property is True
3. Generate tokens on the service side
4. Service-side intercept request verification token process
First step: Create interceptors, execute interception before method execution
Step two: Determine whether the request method
Step three: Determine whether the method is a login method
Step three: Determine whether a method that requires permission validation
5. Application in the project
Attach the Interceptor source code
PackageCom.pjb.springbootjjwt.interceptor;ImportCom.auth0.jwt.JWT;ImportCom.auth0.jwt.JWTVerifier;ImportCom.auth0.jwt.algorithms.Algorithm;Importcom.auth0.jwt.exceptions.JWTDecodeException;Importcom.auth0.jwt.exceptions.JWTVerificationException;ImportCom.pjb.springbootjjwt.annotation.PassToken;ImportCom.pjb.springbootjjwt.annotation.UserLoginToken;ImportCom.pjb.springbootjjwt.entity.User;ImportCom.pjb.springbootjjwt.service.UserService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.web.method.HandlerMethod;ImportOrg.springframework.web.servlet.HandlerInterceptor;ImportOrg.springframework.web.servlet.ModelAndView;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.lang.reflect.Method;/** * @authorJinbin * @date 2018-07-08 20:41*/ Public classAuthenticationinterceptorImplementshandlerinterceptor {@Autowired userservice userservice; @Override Public BooleanPrehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object object)throwsException {//remove tokens from the HTTP request headerString token = Httpservletrequest.getheader ("token"); //if not mapped to method directly through if(! (ObjectinstanceofHandlermethod)) { return true; } Handlermethod Handlermethod=(Handlermethod) object; Method Method=Handlermethod.getmethod (); //Check for Passtoken comments, or skip authentication if(Method.isannotationpresent (Passtoken.class) {Passtoken Passtoken= Method.getannotation (Passtoken.class); if(passtoken.required ()) {return true; } } //check for annotations that require user permissions if(Method.isannotationpresent (Userlogintoken.class) {Userlogintoken Userlogintoken= Method.getannotation (Userlogintoken.class); if(userlogintoken.required ()) {//Perform certification if(token = =NULL) { Throw NewRuntimeException ("No token, please sign in again"); } //get the User ID in tokenString userId; Try{userId= Jwt.decode (token). Getaudience (). Get (0); } Catch(Jwtdecodeexception j) {Throw NewRuntimeException ("401"); } User User=Userservice.finduserbyid (userId); if(User = =NULL) { Throw NewRuntimeException ("User does not exist, please login again"); } //Verify tokenJwtverifier Jwtverifier =Jwt.require (algorithm.hmac256 (User.getpassword ())). build (); Try{jwtverifier.verify (token); } Catch(jwtverificationexception e) {Throw NewRuntimeException ("401"); } return true; } } return true; } @Override Public voidPosthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, ModelAndView Modelandview)throwsException {} @Override Public voidAftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception E )throwsException {}}
View Code
The core steps of JWT application in Javaweb project