Understanding Session and Token-Based Authentication with JWT in Web Applications
The article explains how HTTP’s stateless nature requires session or token mechanisms for preserving user state, compares session‑based and JWT token authentication, details JWT structure, and provides Java code examples for generating, verifying, and extracting token information, while also promoting related services.
HTTP is a stateless protocol used for data transmission between client and server. Because it does not retain state, developers must employ mechanisms such as sessions or tokens to preserve user information during activities like shopping cart management.
1. Session‑Based Authentication
Before JWT became popular, session‑based authentication was the primary method. The server creates a session after a user logs in, stores session data in memory, and sends a session ID to the client via a cookie. The cookie is sent with each request, allowing the server to validate the user. Session cookies without Expires or Max‑Age are deleted when the browser closes, though browsers may restore sessions, keeping the cookie alive.
2. Token‑Based Authentication
Token‑based authentication uses JSON Web Tokens (JWT) and is widely adopted in RESTful APIs. After a successful login, the server issues an encrypted JWT that the client stores (commonly in localStorage ) and includes in subsequent requests. The server validates the token on each request, ensuring the request originates from the authenticated user.
JWT consists of three Base64‑URL parts separated by dots: Header , Payload , and Signature (e.g., xxxxx.yyyyy.zzzzz ). The header and payload are Base64‑encoded, and the signature is generated using a secret key.
3. JWT Implementation in Java
private static final long EXPIRE_TIME = 60 * 1000 * 60 * 24 * 7; // 7 days
private static String ISSUER = "K_ang";
private static final String SING = "K*&^A%$#N@!G"; // secret key public static String getToken(Map
map) {
Date 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));
}
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;
}
}
public static String getTokenInfo(String token) {
DecodedJWT decode = JWT.decode(token);
return decode.getClaim("userNo").asString();
}A Spring controller example shows how to use the JWT utilities during login:
@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失败");
}
String token = JwtUtils.sign(empNo, empPassword);
emp.setToken(token);
return ResultUtil.success(200, "登录成功", emp);
}The article also includes promotional material inviting readers to join a community, purchase courses, and access exclusive ChatGPT accounts.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.