# 第7节.Nacos中Token过期与保护代码设计
在我们日常的系统开发过程中,当不用传统的Session机制作为会话认证的时候,会采取Token的方式进行系统的认证授权,那么在nacos中,他也采用了token机制进行了认证处理。
这块核心的值得学习的逻辑在NacosClientAuthServiceImpl类中,值得我们学习的就是如下类中的3个关于过期的时间的字段存储:
其中:
tokenTtl代表了token的过期时间
lastRefreshTime代表了最后的刷新时间
tokenRefreshWindow代表了token的保护时间窗口值,通过判断当前时间与上次刷新时间的间隔,是否大于保护时间的安全点,如果大于了则提前进行token的续期。
/**
* TTL of token in seconds.
*/
private long tokenTtl;
/**
* Last timestamp refresh security info from server.
*/
private long lastRefreshTime;
/**
* time window to refresh security info in seconds.
*/
private long tokenRefreshWindow;
public Boolean login(Properties properties) {
try {
if ((System.currentTimeMillis() - lastRefreshTime) < TimeUnit.SECONDS
.toMillis(tokenTtl - tokenRefreshWindow)) {
return true;
}
if (StringUtils.isBlank(properties.getProperty(PropertyKeyConst.USERNAME))) {
lastRefreshTime = System.currentTimeMillis();
return true;
}
for (String server : this.serverList) {
HttpLoginProcessor httpLoginProcessor = new HttpLoginProcessor(nacosRestTemplate);
properties.setProperty(NacosAuthLoginConstant.SERVER, server);
LoginIdentityContext identityContext = httpLoginProcessor.getResponse(properties);
if (identityContext != null) {
if (StringUtils.isNotBlank(identityContext.getParameter(NacosAuthLoginConstant.ACCESSTOKEN))) {
tokenTtl = Long.parseLong(identityContext.getParameter(NacosAuthLoginConstant.TOKENTTL));
tokenRefreshWindow = tokenTtl / 10;
lastRefreshTime = System.currentTimeMillis();
loginIdentityContext = new LoginIdentityContext();
loginIdentityContext.setParameter(NacosAuthLoginConstant.ACCESSTOKEN,
identityContext.getParameter(NacosAuthLoginConstant.ACCESSTOKEN));
}
return true;
}
}
} catch (Throwable throwable) {
SECURITY_LOGGER.warn("[SecurityProxy] login failed, error: ", throwable);
return false;
}
return false;
}