package cn.hshb.analysis.core.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Date; public class JWTUtil { private final static Log logger = LogFactory.getLog(JWTUtil.class); private static final String SECRET = "n7B1pIPG#F!#1RQ7M1HJwS53$Bn#@H56W@Zc$4x3"; private static final String EXP = "exp"; private static final String PAYLOAD = "payload"; /** * get jwt String of object * * @param object the POJO object * @param maxAge the milliseconds of life time * @return the jwt token */ public static <T> String sign(T object, long maxAge) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTCreator.Builder signer = JWT.create(); signer.withClaim(PAYLOAD, JSONObject.toJSONString(object)); long expire = System.currentTimeMillis() + maxAge; signer.withExpiresAt(new Date(expire)); return signer.sign(algorithm); } catch (Exception e) { return null; } } /** * get the object of jwt if not expired * * @return POJO object */ public static <T> T unsign(String token, Class<T> classT) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); //Reusable verifier instance DecodedJWT jwt = verifier.verify(token); Claim claim = jwt.getClaim(PAYLOAD); return JSON.parseObject(claim.asString(), classT); } catch (Exception e) { return null; } } public static void main(String[] args) throws Exception { Page page = new Page(); String token = JWTUtil.sign(page, 3600000); logger.info(token); //Thread.sleep(1200); //token += "a"; Page currentPage = JWTUtil.unsign(token, Page.class); logger.info(currentPage); /*JWTCreator.Builder signer = JWT.create(); signer.withClaim("user", "s"); long expire = System.currentTimeMillis() + 2000 * 1000; signer.withExpiresAt(new Date(expire)); String token = signer.sign(algorithm); logger.info(token); try { DecodedJWT jwt = JWT.decode(token); String issuer = jwt.getIssuer(); Claim claim = jwt.getClaim("user"); Date expiresAt = jwt.getExpiresAt(); logger.info(claim.asString()); logger.info(expiresAt.getTime()); } catch (JWTDecodeException exception) { //Invalid token } algorithm = Algorithm.HMAC256("n7B1pIPG#F!#1RQ7M1HJwS53$Bn#@H56W@Zc$4x33"); JWTVerifier verifier = JWT.require(algorithm) .build(); //Reusable verifier instance DecodedJWT jwt = verifier.verify(token); logger.info(jwt);*/ } }
<!-- jwt token --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>${java-jwt.version}</version> </dependency>
package cn.hshb.analysis.api.controller; import cn.hshb.analysis.core.common.ApiResponse; import cn.hshb.analysis.core.utils.JWTUtil; import cn.hshb.analysis.entity.exception.BizErrorCode; import cn.hshb.analysis.entity.model.UserInfo; import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * @author 作者 * @version V1.0 * @Title: LoginController * @Package cn.hshb.analysis.api.controller * 用于身份登录认证 * @date 2018/2/22 15:14 */ @RestController public class LoginController { private static List<UserInfo> validPeoples = new ArrayList<>(); static { /* * 此处设置可以用于登录的用户身份信息,发布正式环境时需要避免用户名密码过于简单 */ validPeoples.add(new UserInfo("admin", "admin")); validPeoples.add(new UserInfo("admin124", "154123")); validPeoples.add(new UserInfo("admin1223", "addsfs")); } @RequestMapping({"/login"}) public ApiResponse login(@RequestParam String username, @RequestParam String password) { /** * @param:[username, password] * 登录认证 * 第三方系统要调用此系统中的接口必须先调用此接口获取token * @return: cn.hshb.analysis.core.common.ApiResponse * @date:2018/2/22 */ if (username == null || password == null) { return ApiResponse.fail(); } UserInfo user = null; for (UserInfo userInfo : validPeoples) { if (username.equals(userInfo.getUsername())) { user = userInfo; break; } } if (user == null) { return ApiResponse.fail(BizErrorCode.CU_MSG_000002.getCode(), BizErrorCode.CU_MSG_000002.getMsg()); } else { if (!password.equals(user.getPassword())) { return ApiResponse.fail(BizErrorCode.CU_MSG_000007.getCode(), BizErrorCode.CU_MSG_000007.getMsg()); } } JSONObject data = new JSONObject(); data.put("token", JWTUtil.sign(user, 7200 * 1000)); data.put("expire", 7200); return ApiResponse.success(data); } }