Skip to content

Commit

Permalink
[ISSUE #12823] Randomly generate TokenRefreshWindow, Avoid a large nu…
Browse files Browse the repository at this point in the history
…mber of logins causing pressure on the Nacos server. (#13046)
  • Loading branch information
lucky8987 authored Jan 21, 2025
1 parent 90d3469 commit b4d9642
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.auth.impl.process.HttpLoginProcessor;
import com.alibaba.nacos.common.utils.RandomUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext;
import com.alibaba.nacos.plugin.auth.api.RequestResource;
Expand All @@ -35,6 +36,7 @@
* @author wuyfee
*/

@SuppressWarnings("checkstyle:SummaryJavadoc")
public class NacosClientAuthServiceImpl extends AbstractClientAuthService {

private static final Logger SECURITY_LOGGER = LoggerFactory.getLogger(NacosClientAuthServiceImpl.class);
Expand Down Expand Up @@ -97,7 +99,7 @@ public Boolean login(Properties properties) {
if (identityContext != null) {
if (identityContext.getAllKey().contains(NacosAuthLoginConstant.ACCESSTOKEN)) {
tokenTtl = Long.parseLong(identityContext.getParameter(NacosAuthLoginConstant.TOKENTTL));
tokenRefreshWindow = tokenTtl / 10;
tokenRefreshWindow = generateTokenRefreshWindow(tokenTtl);
lastRefreshTime = System.currentTimeMillis();

LoginIdentityContext newCtx = new LoginIdentityContext();
Expand All @@ -124,4 +126,15 @@ public LoginIdentityContext getLoginIdentityContext(RequestResource resource) {
public void shutdown() throws NacosException {

}

/**
* Randomly generate TokenRefreshWindow, Avoid a large number of logins causing pressure on the Nacos server.
* @param tokenTtl TTL of token in seconds.
* @return tokenRefreshWindow, numerical range [tokenTtl/15 ~ tokenTtl/10]
*/
public long generateTokenRefreshWindow(long tokenTtl) {
long startNumber = tokenTtl / 15;
long endNumber = tokenTtl / 10;
return RandomUtils.nextLong(startNumber, endNumber);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,12 @@ void testReLogin() {
//when
assertTrue(nacosClientAuthService.login(properties));
}

@Test
void testGenerateTokenWithInvalidToken() {
NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl();
long tokenTtl = 18000L;
long tokenRefreshWindow = nacosClientAuthService.generateTokenRefreshWindow(tokenTtl);
assertTrue(tokenRefreshWindow <= tokenTtl / 10);
}
}

0 comments on commit b4d9642

Please sign in to comment.