Jwt Token


๐Ÿ”Ž JWT Token

๊ณต์‹ ๋ฌธ์„œ

์ž˜ ์ •๋ฆฌ๋œ ๋ธ”๋กœ๊ทธ


๐Ÿ”Ž ๋™์ž‘ ์›๋ฆฌ

ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋กœ๊ทธ์ธ์„ ํ•˜๋ฉด ์„œ๋ฒ„์—์„œ Jwt Token์„ ๋ฐœ๊ธ‰ํ•ด์ค€๋‹ค.

ํด๋ผ์ด์–ธํŠธ๋Š” ๋ฐœ๊ธ‰ ๋ฐ›์€ Jwt Token์„ ์•ž์œผ๋กœ ์žˆ์„ ๋ชจ๋“  ์š”์ฒญ์— ํ•จ๊ป˜ ๋ณด๋‚ธ๋‹ค.

์™œ๋ƒ๋ฉด ์š”์ฒญ ๋ณด๋‚ด๋Š” ํด๋ผ์ด์–ธํŠธ๋ฅผ ์‹๋ณ„ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.


๐Ÿ”Ž ๊ตฌ์กฐ

Header + Payload + Signature


Header

์šฐ์„  Jwt Token์˜ Header๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.

๋ณดํ†ต header์—๋Š” ํ† ํฐ ํƒ€์ž…(JWT), ์•”ํ˜ธํ™” ์•Œ๊ณ ๋ฆฌ์ฆ˜(alg)์ด ๋“ค์–ด๊ฐ„๋‹ค.

HashMap์€ ์ˆœ์„œ๋Š” ๋ณด์žฅ์ด ์•ˆ๋œ๋‹ค.

// JWT Header
private static Map<String, Object> createHeader() {
	Map<String, Object> header = new HashMap<>();
	header.put("alg","HS256");
	header.put("typ","JWT");
	return header;
}


Payload

ํ† ํฐ์—์„œ ์‚ฌ์šฉ์ž์— ๋Œ€ํ•œ ์ •๋ณด์˜ ์กฐ๊ฐ์ธ Claim์„ ์ €์žฅํ•œ๋‹ค.

claim์—๋Š” ๋‹ค์–‘ํ•œ ์ •๋ณด๊ฐ€ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋Š”๋ฐ ํฌ๊ฒŒ ์„ธ๊ฐ€์ง€๋กœ ๋ถ„๋ฅ˜๋œ๋‹ค.

  • ๋“ฑ๋ก๋œ ํด๋ ˆ์ž„(Registered Claim)

  • ๊ณต๊ฐœ ํด๋ ˆ์ž„(Public Claim)

  • ๋น„๊ณต๊ฐœ ํด๋ ˆ์ž„(Private Claim)

// JWT Claims
private static Map<String, Object> createClaims(LoginVo loginVo) {
	Map<String, Object> claims = new HashMap<>();
	claims.put("email",loginVo.getEmail());
	claims.put("seq", loginVo.getUserSeq());
	claims.put("authCode", loginVo.getAuthCode());
	return claims;
}


Signature

๋ฉ”์‹œ์ง€๊ฐ€ ๋„์ค‘์— ๋ณ€๊ฒฝ๋˜์ง€ ์•Š์•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋œ๋‹ค.

Signature๋ž€ Header์™€ Payload๋ฅผ BASE64๋กœ ์ธ์ฝ”๋”ฉํ•œ ๊ฐ’์„ ํ•ฉ์นœ ํ›„,

์ฃผ์–ด์ง„ SecretKey๋กœ ํ•ด์‰ฌ์•„์—ฌ ์ƒ์„ฑ๋œ ๊ฐ’์„ ๋งํ•œ๋‹ค.


์•„๋ž˜์˜ ์ฝ”๋“œ๋Š” secetKey๋ฅผ ๋ฐ”์ดํŠธ๋กœ ๋ฐ”๊ฟ”์คฌ๋‹ค.

์ถ”ํ›„์— ํ† ํฐ์„ ์ƒ์„ฑํ•  ๋•Œ secetKey๋ฅผ ๋ฐ”์ดํŠธ๋กœ ๋„ฃ์–ด์ค˜์•ผ ํ•ด์„œ ๊ทธ๋Ÿฐ๋‹ค๊ณ  ํ•œ๋‹ค.

public static Key createSigningKey() {
	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	return new SecretKeySpec(apiKeySecretBytes,SignatureAlgorithm.HS256.getJcaName());
}


Generate Token

setSubject : ํ† ํฐ ์ œ๋ชฉ (ํ† ํฐ์—์„œ ์‚ฌ์šฉ์ž์— ๋Œ€ํ•œ ์‹๋ณ„๊ฐ’์ด ๋œ๋‹ค.)

ํ† ํฐ ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ์„ค์ •์€ Calnedar ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

public static String generateJwtToken(LoginVo loginVo) {
	String builder = Jwts.builder()
			// header
			.setHeader(createHeader())

			// claim
			.setSubject(loginVo.getEmail())
			.setClaims(createClaims(loginVo))
			.setIssuedAt(new Date(System.currentTimeMillis()))
			.setExpiration(createExpireDateForOneDay())
			
			// signature (HS256๊ณผ Key๋กœ Sign)
			.signWith(SignatureAlgorithm.HS256, createSigningKey())
			
			// ํ† ํฐ ์ƒ์„ฑ
			.compact();
	return builder;
}