JWT profile

Json Web Token (JWT) : Json network Token is an open jSON-based standard (RFC 7519) for transferring claims between network application environments. JWT is a portable, secure cross-platform transport format that defines a compact, self-contained way to securely transfer information between communication parties in JSON objects. The information is trusted because of the digital signature.

Implementation steps:

Environmental spring boot

1. Add JWT dependencies
<dependency> <groupId>com.auth0</groupId> <artifactId> Java -jwt</artifactId> <version>3.8.1</version> </dependency> <dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.9.1</version> </dependency>Copy the code
2. Create the Annotation package under SRC

Create a new custom annotation class JwtToken

package com.qf.tyleryue_one.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Custom annotation: Methods said before need to intercept * / @ Target ({ElementType METHOD, ElementType. TYPE}) @ Retention (RetentionPolicy. RUNTIME) public @ interface JwtToken { }Copy the code
3. Create utils package under SRC

Create a custom JwtUtils utility class

package com.qf.tyleryue_one.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import jdk.internal.org.objectweb.asm.TypeReference; import java.util.Date; Public class JwtUtils {private final static long EXPIRE_TIME=5*60*1000; private final static long EXPIRE_TIME=5*60*1000; Private final static String SECRECT="Tyler_Yue_key"; Public static String sign(String userId){exipre_date = new Date(system.currentTimemillis ()) + EXPIRE_TIME); // Create token JWTCreator.Builder Builder = jwt.create (); WithAudience (userID); // Add tokenbuilder to JWT playload; // Add tokenbuilder to userID playload; WithExpiresAt (exiPRE_date); Algorithm Algorithm = algorithm.hmac256 (SECRECT); String sign = builder.sign(algorithm); return sign; Public static Boolean verifyToken(String token){try {// Generate verifyToken Algorithm Algorithm = Algorithm.HMAC256(SECRECT); JWTVerifier build = jwt.require (algorithm).build(); Return true; } catch (Exception e) {throw new RuntimeException(" token expired "); }}}Copy the code
4. Create the VO package under SRC

Encapsulates an object that returns the user with a token

package com.qf.tyleryue_one.vo; import com.alibaba.druid.filter.AutoLoad; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * wrap a user object that returns a token */ @data@allargsconstructor @noargsconstructor public class TokenVo {// User name private String usernaem; // Token name private String token; }Copy the code
5. Example Controller layer user login Service Login with a token
package com.qf.tyleryue_one.controller; import com.qf.tyleryue_one.entity.VueUser; import com.qf.tyleryue_one.service.VueUserService; import com.qf.tyleryue_one.utils.JwtUtils; import com.qf.tyleryue_one.vo.Msg; import com.qf.tyleryue_one.vo.TokenVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.UUID; @controller public class VueUserController {@autoWired private VueUserService VueUserService; @RequestMapping(value = "/dealLogin",method = RequestMethod.POST) @CrossOrigin @ResponseBody public Msg login(@RequestBody VueUser vueUser){ VueUser vueUser1 = vueUserService.selectByUsername(vueUser.getUsername()); if (vueUser1! =null){if (vueUser1.getPassword().equals(vueuser.getPassword ())){ /// Generate a String randomly without userID String UserID = uuID.randomuuid ().toString(); String token = JwtUtils.sign(userid); TokenVo TokenVo = new TokenVo(vueuser.getUsername (), token); Return new Msg(200," login succeeded,token issued ",tokenVo); }else {return new Msg(403," password error ",null); }}else {return new Msg(403," user does not exist ",null); }}}Copy the code

At the end

Hope to help you, if you like it, remember to like and follow oh