import cn.hutool.core.util.ObjectUtil; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.jwt.demo.config.UserLoginPermission; import com.jwt.demo.db.bean.UserRole; import com.jwt.demo.db.mapper.UserRoleMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.util.Date; / * *

  • Token tools
  • @author chenlirun
  • @date 2021/7/8 17:27

    */

@Component

public class UserLoginTokenUtil {

/** * Select * @author chenlirun * @date 2021/7/18 17:36 */ @autowired private UserRoleMapper UserRoleMapper; /** * Select * @author chenlirun * @date 2021/7/18 17:36 */ @autowired private UserRoleMapper UserRoleMapper; Private static UserLoginTokenUtil UserLoginTokenUtil; /** * @postConstruct * 1, construct a void method. /** * @postconstruct * 1, construct a void method. It runs when the server loads the Servlet, and only once. * 2. To handle the fact that methods in common utility classes cannot be static modifiers, add this annotation so that methods under this annotation can be executed before the class is initialized. Mapper */ @postConstruct public void init(){userLoginTokenUtil=this; } // Set the token expiration time to 30 minutes. Public static final long EXPIRE_TIME=30*60*1000; /** * generate token signature, * * @author chenlirun * @date 2021/7/8 17:52 */ public static String sign(Long id){date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm Algorithm = algorithm.hmac256 (tokenLogininfo.secret); // Set the JWT token, algorithm.hmac256 () encrypts the token. Algorithm Algorithm = algorithm.hmac256 (tokenLogininfo.secret); Return jwt.create ().withclaim ("id",id) // Set attribute, can be the current login user information, WithExpiresAt (date) // Set the expiration time.withissuedat (new date ()) // Set the current creation time.sign (algorithm); // Set the current creation time. } /** * Verify token * @author chenlirun * @date 2021/7/8 17:56 */ public static Boolean verify(String) token,Long id,String secret){ try { Algorithm algorithm = Algorithm.HMAC256(secret); /** * jwt.require (): validates signature algorithm *.build(): [PerfectMoney download] (https://www.gendan5.com/wallet/PerfectMoney.html) using already provided configuration to create a new reusable JWTVerifier instance. Return: a new Jwtverification instance. */ JWTVerifier verifier = JWT.require(algorithm).withClaim("id", id).build(); verifier.verify(token); return true; }catch (Exception e){ return false; } /** * parse token, id * @author chenlirun * @date 2021/7/9 11:20 */ public static Long getTokenById(HttpServletRequest request){ String token = request.getHeader("token"); /** * Decodes the given Json Web token. * Note that this method does not verify the signature of the token! Use the token only if you trust it or if you have verified it. * Return: decoded JWT. Thrown :JWTDecodeException * - if any part of the token contains an invalid JWT or JSON format for each JWT part. */ DecodedJWT decode = JWT.decode(token); return decode.getClaim("id").asLong(); } /** * Authenticate token * @author chenlirun * @date 2021/7/16 14:56 */ public static Boolean validToken(HttpServletRequest) request, UserLoginPermission tag){ String token = request.getHeader("token"); If (token==null){throw new BaseException(BaseCodeResult.ERROR," currently not login "); } Long userId = UserLoginTokenUtil.getTokenById(request); // Verify the token signature system.out.println (tokenLogininfo.secret); boolean verifySuccess = UserLoginTokenUtil.verify(token, userId, TokenLoginInfo.secret); if(! VerifySuccess){throw new BaseException(BaseCodeResult.ERROR," Token signature is incorrect "); } / / verification access UserRole UserRole = userLoginTokenUtil. UserRoleMapper. SelectByUserId (userId); Byte roleId = userRole.getRoleId(); If (objectutil.isEmpty (userRole)){throw new BaseException(BaseCodeResult.ERROR," this user has no permissions "); } /** * string.indexof () * returns the indexOf the first match of the stator String in this String. * The index returned is the smallest value in k: this. Start with (st, k) if kexists does not have this value, return -1. * STR - The substring to search for. * Returns: specifies the index of the first match in the substring, or -1 if there is no match. */ int i = tag.role().indexOf(String.valueOf(roleId)); If (I == -1){throw new BaseException(BaseCodeResult.ERROR," no access "); } return true; }

}