Backend/spring

[Spring Security] Spring Security ์ž„์‹œ ๊ณ„์ •

dddzr 2025. 2. 23. 17:14

๐Ÿ“Œ Spring Security ์ž„์‹œ ๊ณ„์ •

Security filterChain ์—์„œ ๊ถŒํ•œ ๊ฒ€์‚ฌ๋ฅผ ์„ค์ •ํ•œ ๊ฒฝ์šฐ ์ด๋ฅผ ํ†ต๊ณผํ•˜๊ธฐ ์œ„ํ•ด ๋กœ๊ทธ์ธ์ด ํ•„์š”!!

๊ธฐ๋ณธ ํผ์„ ํ™œ์„ฑํ™” ํ•˜๋ฉด ์ž๋™์œผ๋กœ ๋กœ๊ทธ์ธ์ฐฝ์ด ๋œฌ๋‹ค.

 

์ด๋•Œ DB์—ฐ๊ฒฐ ์ „ ์ด๋ผ๋ฉด ์ž„์‹œ๊ณ„์ •์ด ํ•„์š”ํ•˜๋‹ค.

 

๐Ÿ“– ์ธ์ฆ ํ•„ํ„ฐ

http.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated());

 

๐Ÿ“– ๊ธฐ๋ณธ ๋กœ๊ทธ์ธ ํผ ํ™œ์„ฑํ™”

http.authorizeHttpRequests()
        .anyRequest().authenticated()
    .and()
        .formLogin();  // ๊ธฐ๋ณธ ๋กœ๊ทธ์ธ ํผ ํ™œ์„ฑํ™”

 

๐Ÿ“Œ Spring Security ๊ณ„์ • ์ƒ์„ฑ ๋ฐฉ๋ฒ•

โœ… 1. ์ž๋™ ์ƒ์„ฑ - ๋กœ๊ทธ ํ™•์ธ

Spring Security๋Š” app์ด ์‹œ์ž‘ ๋  ๋•Œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ž„์‹œ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ๋กœ๊ทธ์— ์ถœ๋ ฅํ•œ๋‹ค. 

 

๐Ÿ“– ์˜ˆ์‹œ

  • ๋กœ๊ทธ์—์„œ Using generated security password: <์ž„์‹œ ๋น„๋ฐ€๋ฒˆํ˜ธ>๋ฅผ ์ฐพ๊ธฐ!!
  • Username์€ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ user

 

โœ… 2. ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์„ค์ • ํŒŒ์ผ

application.properties ๋˜๋Š” application.yml ํŒŒ์ผ์— ์•„๋ž˜ ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์‚ฌ์šฉ์ž ๊ณ„์ •์„ ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ •

 

๐Ÿ“– ์˜ˆ์‹œ

spring.security.user.name=admin
spring.security.user.password=admin123
  • Username: admin
  • Password: admin123

 

โœ… 3. UserDetailsService ์ด์šฉ

*UserDetailsService ๋Š” Spring Security์—์„œ ์‚ฌ์šฉ์ž ์ธ์ฆ์„ ๋‹ด๋‹นํ•˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋‹ค.

InMemoryUserDetailsManager ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉ์ž ๊ณ„์ •์„ ๋ฉ”๋ชจ๋ฆฌ์— ์ €์žฅ

 

๐Ÿ“– ์˜ˆ์‹œ

@Bean
public UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    
    manager.createUser(User.withUsername("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .build());

    return manager;
}
  • Username: user
  • Password: password