spring cloud oauth2 jwt 使用说明

Dear 丶 2023-07-03 12:20 65阅读 0赞

spring cloud oauth2 jwt 使用说明

*************************

jwt签名、验签相关类及接口

JwtAccessTokenConverter:token转换类

  1. public class JwtAccessTokenConverter implements TokenEnhancer, AccessTokenConverter, InitializingBean {
  2. public static final String TOKEN_ID = "jti";
  3. public static final String ACCESS_TOKEN_ID = "ati";
  4. private static final Log logger = LogFactory.getLog(JwtAccessTokenConverter.class);
  5. private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
  6. private JwtClaimsSetVerifier jwtClaimsSetVerifier = new JwtAccessTokenConverter.NoOpJwtClaimsSetVerifier();
  7. private JsonParser objectMapper = JsonParserFactory.create();
  8. private String verifierKey = (new RandomValueStringGenerator()).generate(); //验签key,默认为随机值
  9. private Signer signer; //签名操作
  10. private String signingKey; //签名key
  11. private SignatureVerifier verifier; //验签操作
  12. *************
  13. 构造方法
  14. public JwtAccessTokenConverter() {
  15. this.signer = new MacSigner(this.verifierKey); //默认使用时MacSigner签名,使用算法HMACSHA256
  16. this.signingKey = this.verifierKey; //签名key默认与verifierKey相同
  17. }
  18. *************
  19. 普通方法
  20. public void setSigningKey(String key) { //设置签名key
  21. Assert.hasText(key);
  22. key = key.trim();
  23. this.signingKey = key;
  24. if (this.isPublic(key)) { //key以"----BEGIN"开头,则使用RsaSigner签名
  25. this.signer = new RsaSigner(key);
  26. logger.info("Configured with RSA signing key");
  27. } else {
  28. this.verifierKey = key;
  29. this.signer = new MacSigner(key);
  30. } //不以"----BEGIN"开头,则使用MacSigner签名
  31. }
  32. private boolean isPublic(String key) {
  33. return key.startsWith("-----BEGIN");
  34. }
  35. public void setVerifierKey(String key) { //设置验签key
  36. public void setVerifier(SignatureVerifier verifier) { //设置签名验证方法
  37. public void setSigner(Signer signer) { //设置签名方法
  38. public Map<String, String> getKey() {
  39. public void setKeyPair(KeyPair keyPair) {
  40. public void setAccessTokenConverter(AccessTokenConverter tokenConverter) {
  41. public AccessTokenConverter getAccessTokenConverter() {
  42. public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
  43. public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
  44. public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
  45. public void setJwtClaimsSetVerifier(JwtClaimsSetVerifier jwtClaimsSetVerifier) {
  46. public JwtClaimsSetVerifier getJwtClaimsSetVerifier() {
  47. public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
  48. public boolean isPublic() {
  49. public boolean isRefreshToken(OAuth2AccessToken token) {
  50. public void afterPropertiesSet() throws Exception {
  51. if (this.verifier == null) {
  52. Object verifier = new MacSigner(this.verifierKey);
  53. //验签优先使用MacSigner
  54. try {
  55. verifier = new RsaVerifier(this.verifierKey); //Rsaverifier创建成功,则使用RsaVerifier验签
  56. } catch (Exception var5) {
  57. logger.warn("Unable to create an RSA verifier from verifierKey (ignoreable if using MAC)");
  58. }
  59. if (this.signer instanceof RsaSigner) {
  60. byte[] test = "test".getBytes();
  61. try {
  62. ((SignatureVerifier)verifier).verify(test, this.signer.sign(test));
  63. logger.info("Signing and verification RSA keys match");
  64. } catch (InvalidSignatureException var4) {
  65. logger.error("Signing and verification RSA keys do not match");
  66. }
  67. } else if (verifier instanceof MacSigner) {
  68. Assert.state(this.signingKey == this.verifierKey, "For MAC signing you do not need to specify the verifier key separately, and if you do it must match the signing key");
  69. } //signingKey、verifierKey要相同,不同抛出异常
  70. this.verifier = (SignatureVerifier)verifier;
  71. }
  72. }

MacSigner:签名、验签类,默认使用的算法为HMACSHA256

  1. public class MacSigner implements SignerVerifier {
  2. private static final String DEFAULT_ALGORITHM = "HMACSHA256";
  3. private final String algorithm;
  4. private final SecretKey key;
  5. **************
  6. 构造方法
  7. public MacSigner(byte[] key) {
  8. public MacSigner(String key) {
  9. public MacSigner(SecretKey key) {
  10. public MacSigner(String algorithm, SecretKey key) {
  11. **************
  12. 普通方法
  13. public byte[] sign(byte[] bytes) {
  14. try {
  15. Mac mac = Mac.getInstance(this.algorithm);
  16. mac.init(this.key);
  17. return mac.doFinal(bytes);
  18. } catch (GeneralSecurityException var3) {
  19. throw new RuntimeException(var3);
  20. } //对bytes进行签名
  21. }
  22. public void verify(byte[] content, byte[] signature) {
  23. byte[] signed = this.sign(content);
  24. if (!this.isEqual(signed, signature)) {
  25. throw new InvalidSignatureException("Calculated signature did not match actual value");
  26. } //检验content、签名内容signature是否想等,不相等则抛出异常
  27. }
  28. public String algorithm() {
  29. return this.algorithm;
  30. }

RsaVerifier:rsa验签类,默认使用的算法为SHA256withRSA

  1. public class RsaVerifier implements SignatureVerifier {
  2. private final RSAPublicKey key;
  3. private final String algorithm;
  4. public RsaVerifier(BigInteger n, BigInteger e) {
  5. this(RsaKeyHelper.createPublicKey(n, e));
  6. }
  7. public RsaVerifier(RSAPublicKey key) {
  8. this(key, "SHA256withRSA");
  9. }
  10. public RsaVerifier(RSAPublicKey key, String algorithm) {
  11. this.key = key;
  12. this.algorithm = algorithm;
  13. }
  14. public RsaVerifier(String key) {
  15. this(RsaKeyHelper.parsePublicKey(key.trim()), "SHA256withRSA");
  16. }
  17. public void verify(byte[] content, byte[] sig) {
  18. try {
  19. Signature signature = Signature.getInstance(this.algorithm);
  20. signature.initVerify(this.key);
  21. signature.update(content);
  22. if (!signature.verify(sig)) {
  23. throw new InvalidSignatureException("RSA Signature did not match content");
  24. }
  25. } catch (GeneralSecurityException var4) {
  26. throw new RuntimeException(var4);
  27. }
  28. }
  29. public String algorithm() {
  30. return this.algorithm;
  31. }
  32. }

SignerVerifier:签名、验签接口

  1. public interface SignerVerifier extends Signer, SignatureVerifier {
  2. }

Signer:签名接口

  1. public interface Signer extends AlgorithmMetadata {
  2. byte[] sign(byte[] var1);
  3. }

SignatureVerifier:验签接口

  1. public interface SignatureVerifier extends AlgorithmMetadata {
  2. void verify(byte[] var1, byte[] var2);
  3. }

AlgorithmMetadata:签名、验签算法

  1. public interface AlgorithmMetadata {
  2. String algorithm();
  3. }

*************************

jwt 存储相关类及接口

JwtTokenStore:jwt存储

  1. public class JwtTokenStore implements TokenStore {
  2. private JwtAccessTokenConverter jwtTokenEnhancer; //token转换类
  3. private ApprovalStore approvalStore; //token使用状态
  4. ***************
  5. 构造方法
  6. public JwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
  7. ***************
  8. 普通方法
  9. public void setApprovalStore(ApprovalStore approvalStore) {
  10. public OAuth2AccessToken readAccessToken(String tokenValue) {
  11. public void removeAccessToken(OAuth2AccessToken token) {
  12. public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
  13. public OAuth2RefreshToken readRefreshToken(String tokenValue) {
  14. public void removeRefreshToken(OAuth2RefreshToken token) {
  15. public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
  16. public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
  17. public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
  18. public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
  19. public OAuth2Authentication readAuthentication(String token) {
  20. public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
  21. public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
  22. public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
  23. public void setTokenEnhancer(JwtAccessTokenConverter tokenEnhancer) {

ApprovalStore:设置客户端使用、禁用接口

  1. public interface ApprovalStore {
  2. boolean addApprovals(Collection<Approval> var1);
  3. boolean revokeApprovals(Collection<Approval> var1);
  4. Collection<Approval> getApprovals(String var1, String var2);
  5. }

Approval:token使用状态

  1. public class Approval {
  2. private String userId;
  3. private String clientId;
  4. private String scope;
  5. private Approval.ApprovalStatus status;
  6. private Date expiresAt;
  7. private Date lastUpdatedAt;
  8. ************
  9. 构造方法
  10. public Approval(String userId, String clientId, String scope, int expiresIn, Approval.ApprovalStatus status) {
  11. public Approval(String userId, String clientId, String scope, Date expiresAt, Approval.ApprovalStatus status) {
  12. public Approval(String userId, String clientId, String scope, Date expiresAt, Approval.ApprovalStatus status, Date lastUpdatedAt) {
  13. ************
  14. 普通方法
  15. public void setUserId(String userId) {
  16. public void setClientId(String clientId) {
  17. public void setScope(String scope) {
  18. public void setStatus(Approval.ApprovalStatus status) {
  19. public void setExpiresAt(Date expiresAt) {
  20. public void setLastUpdatedAt(Date lastUpdatedAt) {
  21. public String getUserId() {
  22. public String getClientId() {
  23. public String getScope() {
  24. public Approval.ApprovalStatus getStatus() {
  25. public Date getExpiresAt() {
  26. public Date getLastUpdatedAt() {
  27. public boolean isCurrentlyActive() {
  28. return this.expiresAt != null && this.expiresAt.after(new Date());
  29. } //过期时间不为null,且在当前时间之后则token存活
  30. public boolean isApproved() {
  31. return this.isCurrentlyActive() && this.status == Approval.ApprovalStatus.APPROVED;
  32. } //token处于存活状态,且approval为Approved,则返回true
  33. public static enum ApprovalStatus {
  34. APPROVED, //使用
  35. DENIED; //拒绝使用
  36. private ApprovalStatus() {
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,65人围观)

还没有评论,来说两句吧...

相关阅读