dromara/Sa-Token · error · SaTokenException

Token-Session 获取失败:token 不能为空

Error message

Token-Session 获取失败:token 不能为空

What it means

Thrown by StpLogicJwtForMixin.getTokenSessionByToken when tokenValue is empty. In JWT Mixin mode, Token-Session data is still stored server-side keyed by the token string, so an empty token cannot address a session. No dedicated code is set (generic SaTokenException).

Source

Thrown at sa-token-plugin/sa-token-jwt/src/main/java/cn/dev33/satoken/jwt/StpLogicJwtForMixin.java:225

 	 */
	@Override
 	public long getTokenTimeout(String tokenValue) {
 		return SaJwtUtil.getTimeout(tokenValue, loginType, jwtSecretKey());
 	}


	// ------------------- Token-Session 相关 -------------------

	/**
	 * 获取指定 token 的 Token-Session,如果该 SaSession 尚未创建,isCreate代表是否新建并返回
	 *
	 * @param tokenValue token值
	 * @param isCreate 是否新建
	 * @return session对象
	 */
	public SaSession getTokenSessionByToken(String tokenValue, boolean isCreate) {
		if(SaFoxUtil.isEmpty(tokenValue)) {
			throw new SaTokenException("Token-Session 获取失败:token 不能为空");
		}
		long timeout = getTokenTimeout(tokenValue);
		return getSessionBySessionId(splicingKeyTokenSession(tokenValue), isCreate, timeout, session -> {
			// 这里是该 Token-Session 首次创建时才会被执行的方法:
			// 		设定这个 SaSession 的各种基础信息:类型、账号体系、Token 值
			session.setType(SaTokenConsts.SESSION_TYPE__TOKEN);
			session.setLoginType(getLoginType());
			session.setToken(tokenValue);
		});
	}


	// ------------------- 会话管理 -------------------  

	/**
	 * [禁用] 根据条件查询Token 
	 */
	@Override

View on GitHub (pinned to ac2c7f6e94)

Solutions

  1. Only call getTokenSession() after ensuring a token is present (StpUtil.getTokenValue() non-empty)
  2. Guard anonymous-permitted handlers: skip session access or check StpUtil.isLogin() first
  3. Send the token in the style your config reads (header/cookie/param) on every request

Example fix

// before
SaSession s = StpUtil.getTokenSession(); // no token in request -> throws

// after
String token = StpUtil.getTokenValue();
if (SaFoxUtil.isNotEmpty(token)) {
    SaSession s = StpUtil.getTokenSession();
    // ...
} else {
    // anonymous path
}
Defensive patterns

Strategy: validation

Validate before calling

String token = StpUtil.getTokenValue();
if (SaFoxUtil.isEmpty(token)) {
    // anonymous request: skip Token-Session usage
}

Prevention

When it happens

Trigger: Calling getTokenSession()/getTokenSessionByToken() (JWT Mixin mode) when the request contains no token — e.g. StpUtil.getTokenValue() returned an empty string and was passed through.

Common situations: Endpoint annotated to allow anonymous access still calls getTokenSession(); token read from a cookie/header that is absent; frontend first request before login obtains a token.

Related errors


AI-assisted analysis of dromara/Sa-Token@ac2c7f6e94 (2026-08-14). Data as JSON: /api/errors/b2cf16ffb01777a4. Report an issue: GitHub.