最后会附上源码
这篇介绍了一个项目中使用的双token登录认证刷新的demo,如需移植到生产项目中,需要根据实际情况做修改。
有个地方需要注意: 我这里刷新产生新的refreshToken时 旧的refreshToken并没有失效,如果不是特别敏感这点的话可以不计较,若是在意的话,那需要自己处理:比如用缓存记录失效的token每次token认证判断是否是失效的token ,如果是的话就返回验证失败。
下面代码中会用到本地redis缓存,如果没有安装或不会用,看下我之前的博文
win7_64 redis下载安装启动服务
springboot集成redis,redis工具类
spingboot redis demo源码
如果对token还不是很了解 , 那么建议先看个我之前写的用java标准处理token的库jwt 实现的一个简单token的生成、认证过程 demo:
基于JWT规范的JWS实现token认证过程,采用JWT库jose4j,附springboot项目 demo源码下载
如果对双token accessToken refreshToken时长设置以及刷新问题 不清楚的可以看下
双token刷新、续期,access_token和refresh_token实效如何设置
demo目录结构及代码
核心代码
java jwt库 jose4j的依赖
<!-- https://mvnrepository.com/artifact/org.bitbucket.b_c/jose4j --><dependency><groupId>org.bitbucket.b_c</groupId><artifactId>jose4j</artifactId><version>0.6.5</version></dependency>
- 1
- 2
- 3
- 4
- 5
- 6
redis 依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
- 1
- 2
- 3
- 4
实体类 User
package com.example.token_demo.entity;/*** @author:* @create: 2019-10-16 09:59**/
public class User {public String account;public String password;public String lastLoginTime;public User(){}public User(String account, String password) {this.account = account;this.password = password;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getLastLoginTime() {return lastLoginTime;}public void setLastLoginTime(String lastLoginTime) {this.lastLoginTime = lastLoginTime;}@Overridepublic String toString() {return "User{" +"account='" + account + '\'' +", lastLoginTime='" + lastLoginTime + '\'' +'}';}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
双token使用web类 AccountController
package com.example.token_demo.controller;import com.example.token_demo.entity.User;
import com.example.token_demo.redis.RedisUtil;
import com.example.token_demo.service.AuthorizationService;
import org.jose4j.json.internal.json_simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.Date;/*** @author:* @create: 2019-10-16 10:02**/
@RestController
public class AccountController {@AutowiredAuthorizationService authorizationService;@AutowiredRedisUtil cache;/*** 注册* @param account* @param password* @return*/@GetMapping("/register")public String register(@RequestParam(name = "account") String account,@RequestParam(name = "password") String password){JSONObject ret = new JSONObject();//简单校验下非空if(account == null || account.equals("") || password == null || password.equals("")){ret.put("code","1");ret.put("desc","account | password can not empty");return ret.toString();}//注册成功,这里没有判断要注册的用户是否存在//...//写入数据库成功后缓存(数据库操作这里就忽略了)cache.set("user"+account,new User(account,password));//responseret.put("code","0");ret.put("desc","ok");return ret.toString();}/*** 登录* @param account* @param password* @return*/@GetMapping("/login")public String login(@RequestParam(name = "account") String account,@RequestParam(name = "password") String password){JSONObject ret = new JSONObject();User user = cache.get("user"+account);//如果缓存account获取user为null,从数据库获取user//...if(user != null && password != null && password.equals(user.getPassword())){//登录成功//创建tokenString accessToken = authorizationService.createAccessIdToken(account);String refreshToken = authorizationService.createRefreshIdToken(account);if(accessToken == null || refreshToken == null){ret.put("code","1");ret.put("desc","failed");return ret.toString();}//缓存当前登录用户 refreshToken 创建的起始时间,这个会在刷新accessToken方法中 判断是否要重新生成(刷新)refreshToken时用到cache.set("id_refreshTokenStartTime"+account,System.currentTimeMillis(),(int)AuthorizationService.refreshTokenExpirationTime);//更新用户最近登录时间user.setLastLoginTime(new Date().toLocaleString());//更新user到数据库成功后缓存(数据库操作这里就忽略了)cache.set("user"+account,user);//responseret.put("code","0");ret.put("desc","ok");ret.put("accessToken",accessToken);ret.put("refreshToken",refreshToken);return ret.toString();}ret.put("code","1");ret.put("desc","failed");return ret.toString();}/*** 用 refreshToken 来刷新 accessToken* @param refreshToken refreshToken* @return*/@GetMapping("/accessToken/refresh/{refreshToken}")public String accessTokenRefresh(@PathVariable("refreshToken") String refreshToken){String account = authorizationService.verifyToken(refreshToken);JSONObject ret = new JSONObject();if(account == null){//通过返回码 告诉客户端 refreshToken过期了,需要客户端就得跳转登录界面ret.put("code","3");//我这里只是演示,返回3表示 refreshToken过期ret.put("desc","failed");return ret.toString();}//创建新的accessTokenString accessToken = authorizationService.createAccessIdToken(account);//下面判断是否刷新 refreshToken,如果refreshToken 快过期了 需要重新生成一个替换掉long minTimeOfRefreshToken = 2*AuthorizationService.accessTokenExpirationTime;//refreshToken 有效时长是应该为accessToken有效时长的2倍 (我在博文里有介绍)Long refreshTokenStartTime = cache.get("id_refreshTokenStartTime"+account);//refreshToken创建的起始时间点//(refreshToken上次创建的时间点 + refreshToken的有效时长 - 当前时间点) 表示refreshToken还剩余的有效时长,如果小于2倍accessToken时长 ,则刷新 refreshTokenif(refreshTokenStartTime == null || (refreshTokenStartTime + AuthorizationService.refreshTokenExpirationTime*1000) - System.currentTimeMillis() <= minTimeOfRefreshToken*1000){//刷新refreshTokenrefreshToken = authorizationService.createRefreshIdToken(account);cache.set("id_refreshTokenStartTime"+account,System.currentTimeMillis(),(int)AuthorizationService.refreshTokenExpirationTime);}//responseret.put("code","0");ret.put("desc","ok");ret.put("accessToken",accessToken);ret.put("refreshToken",refreshToken);return ret.toString();}/*** 查询用户信息* @param accessToken accessToken* @return*/@GetMapping("/user/{accessToken}")public String userInfo(@PathVariable("accessToken") String accessToken){String account = authorizationService.verifyToken(accessToken);System.out.println("account="+account);JSONObject ret = new JSONObject();if(account == null){//通过返回码 告诉客户端 accessToken过期了,需要调用刷新accessToken的接口ret.put("code","2");//我这里只是演示,返回2表示 accessToken过期ret.put("desc","accessToken expire");return ret.toString();}User user = cache.get("user"+account);//如果缓存的user为null 从数据库查询...//...//responseret.put("code","0");ret.put("desc","ok");ret.put("user",user);return ret.toJSONString();}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
keyPair生成,token创建、认证服务类 AuthorizationService
package com.example.token_demo.service;import org.jose4j.json.JsonUtil;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException;
import org.springframework.stereotype.Service;import java.security.PrivateKey;
import java.util.UUID;/*** @author:* @create: 2019-10-16 09:36**/
@Service
public class AuthorizationService {/*** keyId,公钥,私钥 都是用 createKeyPair 方法生成,在本地执行当前类main方法,然后将生成的keyPair 赋值给privateKeyStr和publicKeyStr*/private static String keyId = "0fb0e71291734057be4bd506b5aeb855";private static String privateKeyStr = "{\"kty\":\"RSA\",\"kid\":\"0fb0e71291734057be4bd506b5aeb855\",\"alg\":\"ES256\",\"n\":\"sMEUzPmJQD2QR30PZxBSyutWLQ_HZpekDlJCjw-FUNVJa2LOOEz2Gs2pyPg7GHyBhJSFefdGh4LciCxNuE387unTFYt-kLaSEzPKHLyCI8vwMFCSasPIlqbtlCjSm_R4A-C6gcXrPvFOoCk7dOFM9z5yJXGcwhMq7ZBSDVSoYsio9bmfyNQgdueWeibDL4_YrOhW8PLcDKbNJ7a9CPJRyEp-gRbHABDKVva_Tt98O_KPDNVApzhVbk7dhC2OEvKSRAqiPQT1VVYiOTUY0QOky-52hnYrYKHEoyJzymsrcraQxA-mLk80icBY7WwPupQF9v-3pgN8AmKrs-dgHoXN8Q\",\"e\":\"AQAB\",\"d\":\"Prw5Qstq4Kc5N3Z26hDMIgPHcXUBRDOcYgzmXNqYaelaBshqA2eljjvjAFbCut0uJz2D5pdSrDRRS-_Vog3kMXRCnIoHYRu72x7tpKdv1X7EAJIIdeaJopcbChQ3NG1fz5iK-haieZOyYXxhAwoYhETgxNN_XQ7qlKk9xkd_AJg6LVV5qh4Ackm51yGf8PdpOkU38suIzxRu_-Ra6-CVr5oeTzLowPisQrvpc3poQNwSY-5mBE_l0sGTIocGCG7xuMdbvACACXoTZ1cJigL_6Cvvd8HpL2gMsJVI_KM6ZKO681ZKay_f_ielJL7wxpkfVIFlJtqDYVjybGqYByWlQQ\",\"p\":\"7IwwVhBhCCr_noJkAK5xwllD05nU_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IlqbtlCjSm_R4A-C6gcXrPvFOoCk7dOFM9z5yJXGcwhMq7ZBSDVSoYsio9bmfyNQgdueWeibDL4_YrOhW8PLcDKbNJ7a9CPJRyEp-gRbHABDKVva_Tt98O_KPDNVApzhVbk7dhC2OEvKSRAqiPQT1VVYiOTUY0QOky-52hnYrYKHEoyJzymsrcraQxA-mLk80icBY7WwPupQF9v-3pgN8AmKrs-dgHoXN8Q\",\"e\":\"AQAB\"}";public static long accessTokenExpirationTime = 60;public static long refreshTokenExpirationTime = 60*3;public String createAccessIdToken(String userId) {return createIdToken(userId,accessTokenExpirationTime);}public String createRefreshIdToken(String userId) {return createIdToken(userId,refreshTokenExpirationTime);}public String createIdToken(String account,long expirationTime) {try {//ClaimsJwtClaims claims = new JwtClaims();claims.setGeneratedJwtId();claims.setIssuedAtToNow();//expire timeNumericDate date = NumericDate.now();date.addSeconds(expirationTime);claims.setExpirationTime(date);claims.setNotBeforeMinutesInThePast(1);claims.setSubject("YOUR_SUBJECT");claims.setAudience("YOUR_AUDIENCE");//添加自定义参数,必须是字符串类型claims.setClaim("account", account);//jwsJsonWebSignature jws = new JsonWebSignature();jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);jws.setKeyIdHeaderValue(keyId);jws.setPayload(claims.toJson());PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyStr)).getPrivateKey();jws.setKey(privateKey);//get tokenString idToken = jws.getCompactSerialization();return idToken;} catch (Exception e) {e.printStackTrace();}return null;}/*** jws校验token** @param token* @return 返回 用户账号* @throws JoseException*/public String verifyToken(String token) {try {JwtConsumer consumer = new JwtConsumerBuilder().setRequireExpirationTime().setMaxFutureValidityInMinutes(5256000)//allow some leeway in validating time based claims to account for clock skew//过期后30秒内还能解析成功.setAllowedClockSkewInSeconds(30).setRequireSubject()//.setExpectedIssuer("").setExpectedAudience("YOUR_AUDIENCE")/*RsaJsonWebKey jwk = null;try {jwk = RsaJwkGenerator.generateJwk(2048);} catch (JoseException e) {e.printStackTrace();}jwk.setKeyId(keyId); *///.setVerificationKey(jwk.getPublicKey()).setVerificationKey(new RsaJsonWebKey(JsonUtil.parseJson(publicKeyStr)).getPublicKey()).build();JwtClaims claims = consumer.processToClaims(token);if (claims != null) {String account = (String) claims.getClaimValue("account");System.out.println("认证通过!token payload携带的自定义内容:用户账号account=" + account);return account;}} catch (JoseException e) {e.printStackTrace();} catch (InvalidJwtException e) {e.printStackTrace();}catch (Exception e) {e.printStackTrace();}return null;}/*** 创建jwk keyId , 公钥 ,秘钥*/public static void createKeyPair(){String keyId = UUID.randomUUID().toString().replaceAll("-", "");RsaJsonWebKey jwk = null;try {jwk = RsaJwkGenerator.generateJwk(2048);} catch (JoseException e) {e.printStackTrace();}jwk.setKeyId(keyId);jwk.setAlgorithm(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);String publicKey = jwk.toJson(RsaJsonWebKey.OutputControlLevel.PUBLIC_ONLY);String privateKey = jwk.toJson(RsaJsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);System.out.println("keyId="+keyId);System.out.println();System.out.println("公钥 publicKeyStr="+publicKey);System.out.println();System.out.println("私钥 privateKeyStr="+privateKey);}public static void main(String[] args){//create key paircreateKeyPair();}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
本地生成keyPair,本地运行AuthorizationService main方法生成keyPair 覆盖代码中的keyId、privateKeyStr和publicKeyStr。 如果不是泄漏了不用更换.
启动项目
1 先启动本地 redis 服务
2 启动token demo程序
测试
测试工具 Postman
1 注册
Postman 新建访问 http://127.0.0.1:8081/register?account=zhangsan&password=123456
2 登录
Postman GET方式 访问 http://127.0.0.1:8081/login?account=zhangsan&password=123456
注意 ,为了快速测试, 我特意将 accessToken 过期时间设置1分钟,refreshToken过期时间3分钟
3 查询用户信息 (用accessToken)
Postman GET方式 访问 http://127.0.0.1:8081/user/{accessToken}
-
登录后1分钟内 查询user信息
-
登录后1分钟40秒 查询user信息 (1分30内 accessToken都是有效的,原因解析token设置了 setAllowedClockSkewInSeconds(30),token过期了还能延长30秒有效 )
返回提示 accessToken过期,这时客户端需要 调用刷新accessToken接口(不要跳转登录页面)
4 刷新accessToken (用refreshToken)
Postman GET方式 访问 http://127.0.0.1:8081/accessToken/refresh/{refreshToken}
-
登录后 2分钟之前 刷新accessToken
只有 accessToken 会被刷新,refreshToken虽然我返回了 但是值还是登录返回的refreshToken值 ,如下: -
登录后 2分钟 到 3分钟 内 刷新accessToken
accessToken 和 refreshToken 都会被刷新,如下: -
登录后 3分40秒 刷新accessToken
报错返回提示 refreshToken 过期,如下:
这时客户端 需要跳转到 登录页面重新登录
源码网盘下载
链接:https://pan.baidu.com/s/15oPRcDtjcdXUmDxqji0Jog
提取码:gx9p