|
@@ -1,6 +1,7 @@
|
|
package io.github.nnkwrik.authservice.token;
|
|
package io.github.nnkwrik.authservice.token;
|
|
|
|
|
|
import com.auth0.jwt.JWT;
|
|
import com.auth0.jwt.JWT;
|
|
|
|
+import com.auth0.jwt.JWTCreator;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.auth0.jwt.interfaces.RSAKeyProvider;
|
|
import com.auth0.jwt.interfaces.RSAKeyProvider;
|
|
import io.github.nnkwrik.common.dto.JWTUser;
|
|
import io.github.nnkwrik.common.dto.JWTUser;
|
|
@@ -9,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Component;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
|
|
+import java.lang.reflect.Field;
|
|
import java.security.interfaces.RSAPrivateKey;
|
|
import java.security.interfaces.RSAPrivateKey;
|
|
import java.security.interfaces.RSAPublicKey;
|
|
import java.security.interfaces.RSAPublicKey;
|
|
import java.time.Instant;
|
|
import java.time.Instant;
|
|
@@ -47,32 +49,23 @@ public class TokenCreator {
|
|
}
|
|
}
|
|
};
|
|
};
|
|
|
|
|
|
- public String create(JWTUser jwtUser) {
|
|
|
|
|
|
+ public String create(JWTUser jwtUser) throws IllegalAccessException {
|
|
Algorithm algorithm = Algorithm.RSA256(keyProvider);
|
|
Algorithm algorithm = Algorithm.RSA256(keyProvider);
|
|
//一天后过期
|
|
//一天后过期
|
|
Date expire = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));
|
|
Date expire = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));
|
|
|
|
|
|
- String token = JWT.create()
|
|
|
|
- .withClaim("openId", jwtUser.getOpenId())
|
|
|
|
- .withClaim("nickName", jwtUser.getNickName())
|
|
|
|
- .withClaim("avatarUrl", jwtUser.getAvatarUrl())
|
|
|
|
- .withExpiresAt(expire)
|
|
|
|
- .sign(algorithm);
|
|
|
|
|
|
+ JWTCreator.Builder builder = JWT.create();
|
|
|
|
|
|
- return "Bearer " + token;
|
|
|
|
- }
|
|
|
|
|
|
+ //通过反射构造token字符串
|
|
|
|
+ for (Field field : jwtUser.getClass().getDeclaredFields()) {
|
|
|
|
+ field.setAccessible(true);
|
|
|
|
+ String value = (String) field.get(jwtUser);
|
|
|
|
+ String name = field.getName();
|
|
|
|
+ builder.withClaim(name, value);
|
|
|
|
+ }
|
|
|
|
|
|
- public String create(String openId, String nickName, String avatarUrl) {
|
|
|
|
- Algorithm algorithm = Algorithm.RSA256(keyProvider);
|
|
|
|
- //一天后过期
|
|
|
|
- Date expire = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));
|
|
|
|
|
|
+ String token = builder.withExpiresAt(expire).sign(algorithm);
|
|
|
|
|
|
- String token = JWT.create()
|
|
|
|
- .withClaim("openId", openId)
|
|
|
|
- .withClaim("nickName", nickName)
|
|
|
|
- .withClaim("avatarUrl", avatarUrl)
|
|
|
|
- .withExpiresAt(expire)
|
|
|
|
- .sign(algorithm);
|
|
|
|
|
|
|
|
return "Bearer " + token;
|
|
return "Bearer " + token;
|
|
}
|
|
}
|