43 Star 166 Fork 141

HuaweiCloudDeveloper / saas-housekeeper

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JwtGenerateTokenUtil.java 1.91 KB
一键复制 编辑 原始数据 按行查看 历史
huaweicloud 提交于 2022-12-16 11:34 .
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
*/
package com.huawei.housekeeper.utils;
import com.huawei.housekeeper.constants.CommonConstants;
import com.huawei.housekeeper.dao.entity.User;
import com.huawei.saashousekeeper.context.TenantContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 生成jwt
*
* @author y00464350
* @since 2022-02-11
*/
@Component
public class JwtGenerateTokenUtil {
private static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
@Value("${jwt.tokenHead}")
private String tokenHead;
/**
* 根据用户信息生成token
*
* @param user 用户信息
*/
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
claims.put(Claims.SUBJECT, user.getUserId());
claims.put(CommonConstants.User.USER_NAME, user.getUserName());
claims.put(CommonConstants.User.ROLE, user.getUserRole());
claims.put(CLAIM_KEY_CREATED, new Date(System.currentTimeMillis()));
claims.put(CommonConstants.User.USER_DOMAIN, TenantContext.getDomain());
SecretKey secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), SignatureAlgorithm.HS512.getJcaName());
return tokenHead + Jwts.builder()
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(secretKey)
.compact();
}
}
Java
1
https://gitee.com/HuaweiCloudDeveloper/saas-housekeeper.git
git@gitee.com:HuaweiCloudDeveloper/saas-housekeeper.git
HuaweiCloudDeveloper
saas-housekeeper
saas-housekeeper
master-dev

搜索帮助