Understanding Session and Token‑Based Authentication with JWT in Java
This article explains the stateless nature of HTTP, compares session‑based and token‑based authentication, describes JWT structure and security considerations, and provides Java code examples for implementing login, token generation, verification, and extraction in a backend application.
HTTP is a stateless protocol used for data transfer between clients and servers, which requires mechanisms such as sessions or tokens to preserve user state during interactions like online shopping.
1. Session‑based authentication – Before JWT, authentication relied on server‑managed sessions where the server stored user data in memory and the client held a session cookie without an explicit expiration. Browsers may restore sessions, making the cookie appear persistent.
When a user logs in, the server creates a session, stores session data, and sends a session ID via a cookie. The server validates the session ID on each request and deletes the session data upon logout.
2. Token‑based authentication – Modern applications often use JSON Web Tokens (JWT) for stateless authentication, especially in RESTful APIs. After a successful login, the server issues a signed JWT that the client stores (commonly in localStorage ) and includes in subsequent requests.
The JWT contains three Base64‑URL parts (header, payload, signature) and is compact for transmission. The token carries user claims, allowing the server to verify the token on each request without maintaining session state.
Example code for storing a token in localStorage:
localStorage.setItem("key", "value");
JWT structure
Header • Payload • Signature (e.g., xxxxx.yyyyy.zzzzz )
Because JWTs are sent with every request and contain all necessary user information, they scale better than session cookies, though sensitive data should be avoided or encrypted.
3. JWT implementation in Java
// Define JWT expiration time (7 days)
private static final long EXPIRE_TIME = 60 * 1000 * 60 * 24 * 7;
// Issuer
private static String ISSUER = "K_ang";
/* Secret key */
private static final String SING = "K*&^A%$#N@!G";
/**
* Generate token
*/
public static String getToken(Map
map) {
Date date = null;
try {
date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
JWTCreator.Builder builder = JWT.create()
.withIssuer(ISSUER)
.withExpiresAt(date);
map.forEach((k, v) -> {
builder.withClaim(k, v);
});
return builder.sign(Algorithm.HMAC256(SING));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Verify token
*/
public static boolean verify(String token, String userNo) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SING))
.withClaim("userNo", userNo)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Get token info
*/
public static String getTokenInfo(String token) {
DecodedJWT decode = JWT.decode(token);
return decode.getClaim("userNo").asString();
}Login endpoint example using the generated JWT:
@PostMapping("/login")
public Result login(@PathParam("empNo") String empNo, @PathParam("empPassword") String empPassword) {
if (empNo == null || "".equals(empNo)) {
return ResultUtil.error(103, "请输入用户名,用户名不能为空");
}
if (empPassword == null || "".equals(empPassword)) {
return ResultUtil.error(103, "请输入密码,密码不能为空");
}
Emp emp = empService.login(empNo, empPassword);
if (emp == null) {
return ResultUtil.error(103, "用户不存在,获取token失败");
}
if (emp.getEmpPassword() == null || !emp.getEmpPassword().equals(empPassword)) {
return ResultUtil.error(103, "密码错误,获取token失败");
}
// Generate normal token
String token = JwtUtils.sign(empNo, empPassword);
emp.setToken(token);
return ResultUtil.success(200, "登录成功", emp);
}In summary, JWTs provide a scalable, stateless authentication method for modern web applications, but developers must handle token storage securely and avoid embedding sensitive data.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.