Backend Language/Spring boot(Java)

[Principal] ๋กœ๊ทธ์ธ ๋œ ์œ ์ €์˜ ์ •๋ณด๋ฅผ JWT(Token)๋กœ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ

chaerlo127 2022. 2. 12. 00:21
728x90

๊ทธ ์ „๊นŒ์ง€๋Š” api์—์„œ ์ง์ ‘ userid๋ฅผ ๊ฑด๋‚ด๊ณ 
JPA CRUD FindByUserId๋ฅผ ํ†ตํ•ด ์œ ์ €์˜ ์ •๋ณด๋ฅผ ๋ถˆ๋Ÿฌ์™”์—ˆ๋‹ค.
ํ•˜์ง€๋งŒ ํšŒ์›๊ฐ€์ž…์„ ํ•˜๊ณ , ๋กœ๊ทธ์ธ์„ ํ•˜๊ฒŒ ๋˜๋ฉด token์„ ์ œ๊ณตํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ
UMC APP API๋ฅผ ํŒ€์›๋ถ„๊ป˜์„œ ์ƒ์„ฑํ•ด์ฃผ์…จ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด, token(authorization์— ์žˆ๋Š”)๋ฅผ ๊ณ„์† ์‚ฌ์šฉํ•ด์„œ json์„ ๋ฐ›์•„์™€์•ผํ•˜๋Š” ์ƒํ™ฉ์—์„œ๋Š”
userId๋ฅผ ๋ณด๋‚ด์ง€ ์•Š๊ณ  jwt๋ฅผ ํ†ตํ•ด์„œ ์ •๋ณด๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒํ•˜๋Š”
์˜๋ฌธ์ด ๋“ค์—ˆ๋‹ค.

์ด์— ๋ฐœ๊ฒฌํ•˜๊ฒŒ ๋œ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์ค‘,
๐Ÿ’ป๋™์•„๋ฆฌ ์•ฑ ํ”„๋กœ์ ํŠธ์—์„œ๋Š” Principal์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค.
(@AuthenticationPrincipal ์ด๋‚˜ SecurityContextHolder, Authentication ๋ชจ๋‘ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ์—๋Ÿฌ ๋‚จ,, ์ด์œ ๋ฅผ ๋ชจ๋ฅด๊ฒ ์›€,,)
-> ๋‚˜๋จธ์ง€ ๋ฐฉ์‹์€ ๋ธ”๋กœ๊ทธ ์ถœ์ฒ˜์— ๋ชจ๋‘ ๋‹ด๋„๋ก ํ•˜๊ฒ ๋‹ค ์–ธ์  ๊ฐ€ ๋˜ ์“ธ ์ผ์ด ์žˆ๊ธŒ์ œ,,

 

โญPrincipal

ํšŒ์›๊ฐ€์ž…์„ ํ•˜๋ฉด jwt token ๊ฐ’์„ ๋ฐ›๊ฒŒ ๋˜๋Š”๋ฐ, ์ด๋Š” DB Entity์— userId์™€ ํ•จ๊ป˜ ์ž๋™์œผ๋กœ ์ €์žฅ์ด ๋œ๋‹ค. token ๊ฐ’์„ ์•Œ๋ฉด userId์˜ ๊ฐ’์„ ์•Œ๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

 API์— path๋ฅผ ์ง€์ •ํ•˜๊ณ , token ๊ฐ’์„ ์ž…๋ ฅํ•˜๋ฉด Controller Parameter๋ฅผ ํ†ตํ•ด Principal ๊ฐ’์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. ์ด๋ฅผ Service์— ์ „๋‹ฌํ•˜๊ณ  .getName() Method๋ฅผ ํ†ตํ•ด userId๋ฅผ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. ์ด๋ฅผ findByUserId๋กœ UserEntity์˜ ๊ฐ’์„ ์•Œ๊ฒŒ ๋œ๋‹ค๋ฉด userId๋ฅผ ๋”ฐ๋กœ RequestBody๋‚˜ PathParam์— ์ž‘์„ฑํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

๊ฐ„๋‹จํ•˜๊ฒŒ ์˜ˆ์‹œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ณด์ž๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

//Controller 
@PostMapping(value = "hasUser") 
public ResponseEntity<Boolean> hasUser(Principal principal)
{
	return new ResponseEntity.ok(SentenceService.hasUser(principal)); 
} 

//Service 
public Boolean hasUser(Principal principal){ 
	User user = userRepository.findByUserId(principal.getName()); 
	if(user!=null){return true;} 
	else return false; 
    }


Principal์„ ํ†ตํ•ด token์— ์žˆ๋Š” User์˜ id ๊ฐ’์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” .getName() ์ด๋ผ๋Š” Getter ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
์ด๋ฅผ ํ†ตํ•ด ๋”ฐ๋กœ RequestBody๋‚˜ QueryParam ๋“ฑ์„ ํ†ตํ•ด ์ง์ ‘ userId ๊ฐ’์„ ๋ถˆ์–ด์˜ค์ง€ ์•Š์•„๋„ ๋œ๋‹ค. (Token ๊ฐ’์„ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ณด๋ฅผ ์–ป์œผ๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ)

728x90


[์ถœ์ฒ˜]
๐Ÿ‘€ ์ฒซ ๋ฒˆ์งธ ์ถœ์ฒ˜ ๋ธ”๋กœ๊ทธ
๐Ÿ‘€ ๋‘ ๋ฒˆ์งธ ์ถœ์ฒ˜ ๋ธ”๋กœ๊ทธ

728x90