dromara/Sa-Token · error · SaTokenException

UsernameAndPassword 不能为空

Error message

UsernameAndPassword 不能为空

What it means

SaHttpBasicAccount has a convenience constructor taking a single 'username:password' string. It rejects null/empty input immediately with this exception (no error code set). It guards developer configuration — Basic-auth credentials must be present before any 401 challenge logic can run.

Source

Thrown at sa-token-core/src/main/java/cn/dev33/satoken/httpauth/basic/SaHttpBasicAccount.java:55

	private String password;

	/**
	 * 构造函数
	 * @param username 账号
	 * @param password 密码
	 */
	public SaHttpBasicAccount(String username, String password) {
		this.username = username;
		this.password = password;
	}

	/**
	 * 构造函数
	 * @param usernameAndPassword 账号和密码,冒号隔开
	 */
	public SaHttpBasicAccount(String usernameAndPassword) {
		if(SaFoxUtil.isEmpty(usernameAndPassword)) {
			throw new SaTokenException("UsernameAndPassword 不能为空");
		}
		String[] arr = usernameAndPassword.split(":");
		if(arr.length != 2) {
			throw new SaTokenException("UsernameAndPassword 格式错误,正确格式为:username:password");
		}
		this.username = arr[0];
		this.password = arr[1];
	}

	/**
	 * 获取 账号
	 *
	 * @return username 账号
	 */
	public String getUsername() {
		return this.username;
	}

View on GitHub (pinned to ac2c7f6e94)

Solutions

  1. Supply a non-empty 'username:password' string, ideally from a validated config property
  2. Fail fast at startup if the credential property is blank (add a @Validated @ConfigurationProperties check)
  3. Prefer the two-argument constructor SaHttpBasicAccount(username, password) so emptiness is explicit at each call site

Example fix

// before
String cred = env.getProperty("app.basic", "");
SaHttpBasicAccount acc = new SaHttpBasicAccount(cred); // throws when unset

// after
String cred = env.getRequiredProperty("app.basic"); // fails fast if missing
SaHttpBasicAccount acc = new SaHttpBasicAccount(cred);
Defensive patterns

Strategy: validation

Validate before calling

if (SaFoxUtil.isEmpty(usernameAndPassword)) {
    throw new IllegalArgumentException("basic credentials must be configured");
}
new SaHttpBasicAccount(usernameAndPassword);

Prevention

When it happens

Trigger: new SaHttpBasicAccount("") or new SaHttpBasicAccount(null), typically because the credential string came from config or an environment variable that was never populated.

Common situations: sa-token.basic= left blank in application.yml but passed to the constructor; environment-specific env vars missing in a new deployment; refactoring that moved the constant and left an empty default.

Related errors


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