1.封装token的入参(tokenParam)
public class TokenParam {
@NotBlank(message = "identity-server_token_get_0001::username can not be null")
private String username;
@NotNull(message = "identity-server_token_get_0002::password can not be null")
private String password;
private Integer userType;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
}
2.封装认证信息(IdentityUser)
public class IdentityUser {
private String userId;
private String username;
private Integer userType;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
}
3.建立JwtUtil工具类
private static final String KEY_DECODE_ALGORITHM = "AES";
private static final String RSA_ALGORITHM = "RSA";
private static final String DEFAULT_USER_KEY = "userId";
private static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256; //默认RSA246
三个参数(供业务层调用)
// @Desccription 创建jwt token
public static String createJWT(String key, IdentityUser user, long expireTime) throws GCloudException{
if(signatureAlgorithm == null){
throw new GCloudException("identity_token_jwt_0001::this algorithm is not supported");
}
return createJWT(signatureAlgorithm, key, user, expireTime);
}
四个参数(内部调用)
public static String createJWT(SignatureAlgorithm signatureAlgorithm, String key, IdentityUser user, long expireTime) throws GCloudException{
String token = null;
Key secretKey = null;
Map paramMap = null;
try{
secretKey = getCreateKey(signatureAlgorithm, key);
}catch(GCloudException sex){
throw sex;
}catch(Exception ex){
throw new GCloudException("identity_token_jwt_0003::get secret key failed");
}
Date expDate = new Date(expireTime);
Date nowDate = new Date();
String jwtId = KeyUtil.getUuid();
JwtBuilder builder = Jwts.builder().setId(jwtId)
.setIssuedAt(nowDate)
.setSubject(user.getUserId())
.setExpiration(expDate)
.signWith(signatureAlgorithm, secretKey);
try{
paramMap = ObjectUtil.objectToMap(user);
if(paramMap != null){
paramMap.remove(DEFAULT_USER_KEY);
if(paramMap.size() > 0){
builder.addClaims(paramMap);
}
}
}catch(Exception ex){
throw new GCloudException("identity_token_jwt_0004::get user info faied");
}
try{
token = builder.compact();
}catch(Exception ex){
throw new GCloudException("identity_token_jwt_0005::generate token failed");
}
return token;
}
/*
* @Desccription 根据算法获取加密的key
*/
private static Key getCreateKey(SignatureAlgorithm signatureAlgorithm, String key) throws Exception {
Key result = null;
if(SignatureAlgorithm.RS256.equals(signatureAlgorithm) || SignatureAlgorithm.RS384.equals(signatureAlgorithm) || SignatureAlgorithm.RS512.equals(signatureAlgorithm)){
result = generalRSPublicKey(key);
}else if(SignatureAlgorithm.HS256.equals(signatureAlgorithm) || SignatureAlgorithm.HS384.equals(signatureAlgorithm) || SignatureAlgorithm.HS512.equals(signatureAlgorithm)){
result = generalHSKey(key);
}else{
throw new GCloudException("identity_token_jwt_0008::this algorithm is not supported");
}
return result;
}
/*
* @Desccription
*/
private static Key generalHSKey(String key) throws Exception{
byte[] encodedKey = new Base64().decode(key);
Key secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, KEY_DECODE_ALGORITHM);
return secretKey;
}
/*
* @Desccription 获取秘钥
*/
private static Key generalRSPrivateKey(String key) throws Exception {
byte[] publicKeyBytes = new Base64().decode(key);
byte[] publicKeyRealBytes = new Base64().decode(publicKeyBytes);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyRealBytes);
KeyFactory keyFac = KeyFactory.getInstance(RSA_ALGORITHM);
return keyFac.generatePublic(keySpec);
}
4.建一个token管理器类(TokenManager),以下是该类生成token的方法,调用工具类的creatJWT方法
public Token generateToken(IdentityUser user) throws GCloudException {
Long expireTime = System.currentTimeMillis() + identityServerTokenProp.getVaildTime(UserType.getByValue(user.getUserType()));
String tokenId = JwtUtil.createJWT(identityServerTokenProp.getEncryptKey(), user, expireTime);
Token token = new Token();
token.setUser(user);
token.setTokenId(tokenId);
token.setExpireTime(expireTime);
return token;
}
5.控制器(TokenController)映射的方法
@RequestMapping("token.do")
public RequestResult token(@Validated TokenParam param){
TokenResponse response = userService.token(param);
return new RequestResult(response);
}
6.业务层(TokenService)对应的token(TokenParam param)方法
@Override
public TokenResponse token(@Validated TokenParam param) throws GCloudException {
Integer userType = param.getUserType();
if(userType == null || UserType.getByValue(param.getUserType()) == null){
userType = UserType.USER.getValue();
}
User user = userDao.getUserByNameAndType(param.getUsername(), userType);
if(user == null){
throw new GCloudException("identity-server_token_get_0003::user does not exist");
}
String md5Pwd = "";
try{
md5Pwd = MD5Util.encrypt(param.getPassword());
}catch (Exception ex){
log.error("mgr_user_save_0005,密码md5加密失败", ex);
throw new GCloudException("server_token_get_0004::password encrypt error");
}
if(md5Pwd == null || !md5Pwd.equals(user.getPassword())){
throw new GCloudException("server_token_get_0005::password is not correct");
}
//保存认证用户信息
IdentityUser idUser = new IdentityUser();
idUser.setUsername(user.getUsername());
idUser.setUserId(user.getId());
idUser.setUserType(user.getUserType());
//调用TokenManager的generateToken(IdentityUser idUser)方法
Token token = tokenManager.generateToken(idUser);
TokenResponse response = new TokenResponse();
response.setToken(token);
response.setUserId(user.getId());
return response;
}