๐Ÿ”ฅ TIL - Day 29

Kim Dae Hyunยท2021๋…„ 10์›” 16์ผ
1

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
33/93

ํ”„๋กœ์ ํŠธ๊ฐ€ ๊ฑฐ์˜ ๋งˆ๋ฌด๋ฆฌ๋˜์–ด ์˜ค๋Š˜์€ ํ˜ผ์ž ๊ฐ„๋‹จํ•œ ํ”„๋กœ์ ํŠธ๋ฅผ ๊ตฌ์ƒํ•ด๋ณด๊ณ  ๊ฐœ์ธ๊ณต๋ถ€๋ฅผ ํ–ˆ๋‹ค.

์ด๋ฒˆ ํ”„๋กœ์ ํŠธ์—์„œ ์ธ์ฆ ๋ถ€๋ถ„์„ ๊ตฌํ˜„ํ•˜๋ฉฐ ๊ณ ์ƒ๋„ ํ–ˆ๊ณ  ์•„์ง๋„ ๋ง˜์— ๋“ค์ง€ ์•Š๋Š” ๋ถ€๋ถ„์ด ๋งŽ์•„์„œ ์ดํ›„ Spring ์œผ๋กœ ๋„˜์–ด๊ฐ€๋ฉด ์ข€ ๋” ์ž˜ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋„๋ก spring์—์„œ jwt๋ฅผ ๋‹ค๋ฃจ๋Š” ์—ฐ์Šต์„ ํ–ˆ๋‹ค.

Java์—์„œ JWT๋ฅผ ์œ„ํ•ด ์ œ๊ณต๋˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ํฌ๊ฒŒ 2๊ฐœ๊ฐ€ ์žˆ๋‹ค.

auth0์—์„œ ๋งŒ๋“  Java JWT์™€ okta์—์„œ ๋งŒ๋“  jjwt๊ฐ€ ์žˆ๋‹ค.


๐Ÿ“Œ Okta jjwt

okta์˜ jjwt๋ถ€ํ„ฐ ๊ฐ„๋‹จํ•˜๊ฒŒ ์•Œ์•„๋ณด์ž.

[ Maven ]
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>

[ Gradle ]
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'

Claim ์ƒ์„ฑ๋ฐฉ๋ฒ•

Strint jwtToken = Jwts.builder().addClaims()
    .Map.of(
        "exp", 
        "key1", "value1",
        "key2", "value2", ...
    )   
    .signWith(SignatureAlgorithm.HS256, "JWT_SECRET_KEY")
    .compact();

Payload ํŒŒ์‹ฑ๋ฐฉ๋ฒ• (ํ† ํฐ ๋””์ฝ”๋”ฉ)

Jws<Claims> jwt = Jwts.parser()
    .setSigningKey("JWT_SECRET_KEY")
    .parseClaimsJws(jwtToken);

๐Ÿ“Œ auth0 Java-JWT

๋‹ค์Œ์œผ๋กœ auth0์˜ Java JWT๋ฅผ ๊ฐ„๋‹จํ•˜๊ฒŒ ์•Œ์•„๋ณด์ž.

[ Maven ]
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.18.2</version>
</dependency>

[ Gradle ]

implementation 'com.auth0:java-jwt:3.18.2'

Claim ์ƒ์„ฑ๋ฐฉ๋ฒ•

String jwtToken = JWT.create()
    .withSubject("subject"
    .withExpiresAt(new Date(System.currentTimeMillis() + ... )
    .withClaim("key2", "value2")
    .sign(Algorithm.HMAC256("JWT_SECRET_KEY"));

Payload ํŒŒ์‹ฑ๋ฐฉ๋ฒ• (ํ† ํฐ ๋””์ฝ”๋”ฉ)

DecodedJWT jwt = JWT.require(Algorithm.HMAC256("JWT_SECRET_KEY"))
    .build()
    .verify(jwtToken);

Java JWT๋Š” jjwt์™€ ๋‹ค๋ฅด๊ฒŒ key ์—†์ด ํ† ํฐ์„ ๋””์ฝ”๋”ฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•œ๋‹ค.
์ฆ‰ ํ† ํฐ ๊ฒ€์ฆ์— ์‹คํŒจํ•ด๋„ Claim์„ ๋ณด๊ณ  ํ•„์š”ํ•˜๋‹ค๋ฉด ์•Œ๋งž๊ฒŒ ์‘๋‹ต์„ ๋‚ด๋ ค์ค„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

DecodedJWT token = JWT.decode(jwtToken)
token.getClaims()
profile
์ข€ ๋” ์ฒœ์ฒœํžˆ ๊นŒ๋จน๊ธฐ ์œ„ํ•ด ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ๐Ÿง

0๊ฐœ์˜ ๋Œ“๊ธ€