์ปจํธ๋กค๋ฌ์์ Authentication ์ ๋ณด๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ!โจ ์ค์ ์ ์ด์ ๋งค์ฐ ๊ฐ๋จํด์ง๋๋ค.๋โฆ?
๋ถ์กฑํ ๋ถ๋ถ์ด ์๋ค๋ฉด ๋๊ฐ ๋ด์ฉ ๋ณด์ถฉ์ข ํด์ฃผ์ธ์ ๐ค
์ปจํธ๋กค๋ฌ์์ Authentication ์ ๋ณด๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ!

์กฐ๊ธ ์ต์ง์ค๋ฌ์ด ์์ ์ด๊ธด ํ์ง๋งโฆ ๐
์ปจํธ๋กค๋ฌ์์ ์์ ๊ฐ์ด
@AuthenticationPrincipal
๋ฅผ ์ฌ์ฉํด์ ํ ํฐ ์ ๋ณด๋ฅผ ์ฌ์ฉํ๋ค๊ณ ๊ฐ์ ํด๋ณด๊ฒ ์ต๋๋ค.์ด ๊ฒฝ์ฐ์ ํ
์คํธ ์ฝ๋์์ ๊ทธ๋ฅ ํ
์คํธ๋ฅผ ํ๊ฒ ๋๋ฉด ์๋์ ๊ฐ์ ์ค๋ฅ๋ฅผ ๋ง๋๊ฒ ๋ฉ๋๋ค.
์ด์ ๋ ํ ํฐ ์ ๋ณด๋ฅผ ์ฐพ์ ์๊ฐ ์๊ธฐ ๋๋ฌธ์
๋๋ค. ๐ฑ

๊ทธ๋์ ํ
์คํธ ํ๊ธฐ ์ํด์๋ ํ ํฐ ์ ๋ณด๋ฅผ ์ค์ ํด์ค์ผ ํฉ๋๋ค.
์ด์ ์ธ์คํ๋จ๋จ์์๋ ์๋์ ๊ฐ์ด ํ
์คํธ ํด๋์ค์์ ๋ณ๋์ ๋ฉ์๋๋ฅผ ์ ์ํด์ค์ผ ํ์ต๋๋ค. ๐ซ

โจโจ ์ด๋ฅผ ์กฐ๊ธ ๋ ์์ฝ๊ฒ ์ฌ์ฉํ ์ ์๋๋ก ์ด๋
ธํ
์ด์
ํด๋์ค๋ฅผ ์์ฑํ์ต๋๋ค.

public class WithMockJwtAuthenticationSecurityContextFactory implements WithSecurityContextFactory<WithMockJwtAuthentication> { @Override public SecurityContext createSecurityContext(WithMockJwtAuthentication annotation) { SecurityContext context = SecurityContextHolder.createEmptyContext(); JwtAuthenticationToken authentication = new JwtAuthenticationToken( new JwtAuthentication(annotation.token(), annotation.id(), annotation.username()), null, createAuthorityList(annotation.role()) ); context.setAuthentication(authentication); return context; } }
@Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockJwtAuthenticationSecurityContextFactory.class) public @interface WithMockJwtAuthentication { String token() default "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwicm9sZXMiOlsiVVNFUiJdLCJpc3MiOiJzZmFtIiwiZXhwIjoxNjU4NTkyNTYyLCJpYXQiOjE2NTg1OTI1MzIsInVzZXJJZCI6MSwidXNlcm5hbWUiOiJ0ZXN0MDAifQ.FDkOUzhLvKOYFmjOxRtF-dRDSO2BkoplJTMIyhp0c0ajxOLeZbKuekSyySnCnjVvv_f0Qx8T7a3ZS2OlaSGiDQ"; long id() default 1L; String username() default "test00"; String role() default "USER"; }
ํ ํฐ ์ค์ ์ ํ์ํ ํ๋๋ค๊ณผ ํจ๊ป Default ๊ฐ๋ค์ ์ค์ ํ์ต๋๋ค.
์ด๋ฅผ ์ฌ์ฉํ์ ๋ค๋ฉด ํด๋น ๊ฐ์ผ๋ก ํ ํฐ ์ ๋ณด๊ฐ ์ค์ ๋๊ธฐ ๋๋ฌธ์ ํด๋น ํ๋์ ๊ฐ์ผ๋ก ํ
์คํธ ํด์ฃผ์๋ฉด ๋ฉ๋๋ค.
- ํ ํฐ์
application-mem.yml
์ ํ ์คํธ ํค๋ก ๋ง๋ ๊ฐ์ ๋๋ค. (๋ฐฐํฌ ํ๊ฒฝ์ ์ค์ ํค๋ก ๋ง๋ ํ ํฐ์ ๋ฃ๋๊ฑด ์ํํ ์ ์๊ฒ ์ฃ ? ๐ซ )

ํด๋น ํด๋์ค๋ ๊ณตํต์ ์ผ๋ก ์ฌ์ฉ๋๋ ๊ฐ์ด๊ธฐ ๋๋ฌธ์ Default๊ฐ์ ๋ณ๊ฒฝ์ ํ์๋ค ๊ฒํ ํ์ ํด์ฃผ์ธ์.
โจ ์ค์ ์ ์ด์ ๋งค์ฐ ๊ฐ๋จํด์ง๋๋ค.
์ด๋
ธํ
์ด์
๋ง ์ฌ์ฉํด์ฃผ์๋ฉด ์ด์ ํ ํฐ ์ ๋ณด๊ฐ ์์ ํด๋์ค์์ ์ค์ ๋ ์ ๋ณด๋ก ์ฌ์ฉ๋ฉ๋๋ค.

- ์ด์ ํ ์คํธ๋ฅผ ๋ค์ ํด๋ณด๋ฉด ์ํผํ๊ฒ ์ฑ๊ณตํ๊ฒ ๋ฉ๋๋ค.

๋โฆ?
์ ๋ณด๊ฐ ๋ ํ์ํ๋ค๋ฉด ์๋์ ๋ธ๋ก๊ทธ๊ฐ ์ฐธ๊ณ ๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค. ๐