๐Ÿ’ Spring/Spring Security

9. JWT ์ž„์‹œ ํ† ํฐ์œผ๋กœ ํ•„ํ„ฐ ํ…Œ์ŠคํŠธ

iseunghan 2021. 11. 1. 19:20
๋ฐ˜์‘ํ˜•

์ด ํฌ์ŠคํŠธ๋Š” ๋ฐ์–ด ํ”„๋กœ๊ทธ๋ž˜๋ฐ๋‹˜์˜ ์œ ํŠœ๋ธŒ ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ๋‚˜์„œ ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.

 

ํ† ํฐ์„ ๊ฒ€์ฆ ํ•  ํ•„ํ„ฐ ์ƒ์„ฑ

ํ•„ํ„ฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ํ† ํฐ ๊ฒ€์ฆ์„ ํ–ˆ์„ ๋•Œ, ์œ ํšจํ•˜์ง€ ์•Š๋‹ค๋ฉด ํ•ด๋‹น ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๋” ์ด์ƒ ์ ‘๊ทผํ•˜์ง€ ๋ชปํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

public class MyFilter3 implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        res.setCharacterEncoding("utf-8");

        // ๋งŒ์•ฝ, token์„ ๊ฒ€์ฆํ•˜์—ฌ, Controller์— ์ ‘๊ทผ ์—ฌ๋ถ€ ์„ค์ •!
        if (req.getMethod().equals("POST")) {
            String auth_header = req.getHeader("Authorization");

            if(auth_header.equals("secret")) {
                filterChain.doFilter(req, res);
            } else {
                PrintWriter writer = res.getWriter();
                writer.println("์ธ์ฆ ์•ˆ๋จ");
            }
        } else {
        	filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
  • POST๋กœ ์š”์ฒญ์ด ์™”๋‹ค๋ฉด
    • ํ—ค๋”์— Authorization ๊ฐ’์„ ๊บผ๋ƒ…๋‹ˆ๋‹ค.
    • ํ•ด๋‹น ๊ฐ’์ด ์ž„์‹œ๋กœ ๋งŒ๋“ค์–ด๋†“์€ ํ‚ค ๊ฐ’์ธ secret์ด ๋งž๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.
      • ๋งž๋‹ค๋ฉด, ๊ณ„์† ํ•„ํ„ฐ๋ฅผ ํƒ€๊ฒŒ ๋” ํ•˜๊ณ 
      • ํ‹€๋ฆฌ๋‹ค๋ฉด, "์ธ์ฆ ์•ˆ๋จ" ์ด๋ผ๋Š” ๋ฉ”์„ธ์ง€๋ฅผ ์‘๋‹ตํ•ฉ๋‹ˆ๋‹ค.

 

ํ•ด๋‹น ํ•„ํ„ฐ๋ฅผ Security ์„ค์ •์— ๋“ฑ๋ก

http.addFilterBefore(new MyFilter3(), SecurityContextPersistenceFilter.class);  // securityFilter๊ฐ€ ์‹คํ–‰๋˜๊ธฐ ์ „์—!

 

 

Postman ์œผ๋กœ ํ…Œ์ŠคํŠธ

์ž˜๋ชป๋œ ํ† ํฐ์œผ๋กœ ์š”์ฒญํ–ˆ์„ ๋•Œ

  • ์šฐ๋ฆฌ๊ฐ€ ์ƒ์„ฑํ•œ ํ•„ํ„ฐ์— ๊ฑธ๋ ค์„œ controller์— ์ ‘๊ทผํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.

 

์˜ฌ๋ฐ”๋ฅธ ํ† ํฐ์œผ๋กœ ์š”์ฒญํ–ˆ์„ ๋•Œ

  • controller์—์„œ ์˜ฌ๋ฐ”๋ฅธ ์‘๋‹ต์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค.

 

์ด๋Ÿฐ์‹์œผ๋กœ ์‚ฌ์šฉ์ž๊ฐ€ ์ตœ์ดˆ๋กœ ๋กœ๊ทธ์ธํ•  ๋•Œ, JWT๋ฅผ ์„œ๋ฒ„์—์„œ ์ƒ์„ฑํ•ด์„œ ์ฃผ๋ฉด
์ดํ›„์— ํด๋ผ์ด์–ธํŠธ์—์„œ JWT ํ† ํฐ์„ ๋‹ด์•„ ๋‹ค์‹œ ์„œ๋ฒ„๋กœ ๋กœ๊ทธ์ธ ์š”์ฒญ์„ ๋ณด๋‚ธ๋‹ค๋ฉด JWTํ† ํฐ ๊ฒ€์ฆ์œผ๋กœ ์ œ์ผ ๋จผ์ € ๊ฑธ๋Ÿฌ๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋ฐ˜์‘ํ˜•