728x90
WebSecurityConfigurerAdapter
๊ฐ๋ฐ์๊ฐ SpringSecurity ์ค์ ์ ๋ ์ฝ๊ฒ ๊ตฌํํ๋๋ก ๊ตฌํ๋์ด์๋ค.
์๋ฅผ ์์๋ฐ์ผ๋ฉด class์ @EnableWebSecurity ์ค์ ํด์ค์ผํ๋ค.
URL Matchers ๊ด๋ จ ๊ธฐ๋ฅ
- antMatchers()
- antMatchers("/signup").permitAll()
- "/signup" ์์ฒญ์ ๋ชจ๋์๊ฒ ํ์ฉ
- mvcMatchers()
- mvcMatchers("/signup").permitAll()
- "/signup", "/signup/", "/signup.html" ์ ๊ฐ์ ์ ์ฌ signup ์์ฒญ์ ๋ชจ๋์๊ฒ ํ์ฉํ๋ค.
- regexMatchers()
- ์ ๊ทํํ์์ผ๋ก ๋งค์นญํ๋ค
- requestMatchers
- ์์ ์ธ๊ฐ ๋ชจ๋ requestMatchers๋ก ์ด๋ฃจ์ด์ ธ ์๋ค.
- ๋ช ํํ๊ฒ ์์ฒญ ๋์์ ์ง์ ํ๋ ๊ฒฝ์ฐ์ requestMatchers๋ฅผ ์ฌ์ฉํ๋ค.
์ธ๊ฐ ๊ด๋ จ ์ค์
- http.authorizeRequests()
- ์ธ๊ฐ๋ฅผ ์ค์
- permitAll()
- http.authorizeRequests().antMatchers("/signup").permitAll()
- "/signup" ์์ฒญ์ ๋ชจ๋์๊ฒ ํ์ฉํ๋ค.
- hasRole()
- http.authorizeRequests().antMatchers(HttpMethod.POST, "/notice").hasRole("ADMIN")
- ๊ถํ์ ๊ฒ์ฆ
- authenticated()
- ์ธ์ฆ์ด ๋์๋์ง๋ฅผ ๊ฒ์ฆํ๋ค.
- ignoring()
- ํน์ ๋ฆฌ์์ค์ ๋ํด์ SpringSecurity ์์ฒด๋ฅผ ์ ์ฉํ๊ณ ์ถ์ง ์์๋
- ignoring์ ์ฌ์ฉํ ์ฝ๋๋ permitAll๊ณผ ๋ค๋ฅด๊ฒ SpringSecurity์ ๋์์ ํฌํจํ์ง ์๋๋ค.
- ์ด๋ค ํํฐ๋ ์คํ๋์ง ์์ ์ฑ๋ฅ์ ์ผ๋ก ์ฐ์ํจ
@Override
public void configure(WebSecurity web) {
// ์ ์ ๋ฆฌ์์ค spring security ๋์์์ ์ ์ธ
web.ignoring().antMatchers("/images/**", "/css/**"); // ์๋ ์ฝ๋์ ๊ฐ์ ์ฝ๋
web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}
์์
/**
* Security ์ค์ Config
*/
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// basic authentication
http.httpBasic().disable(); // basic authentication filter ๋นํ์ฑํ
// csrf
http.csrf();
// remember-me
http.rememberMe();
// authorization
http.authorizeRequests()
// /์ /home์ ๋ชจ๋์๊ฒ ํ์ฉ
.antMatchers("/", "/home", "/signup").permitAll()
// hello ํ์ด์ง๋ USER ๋กค์ ๊ฐ์ง ์ ์ ์๊ฒ๋ง ํ์ฉ
.antMatchers("/note").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/notice").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/notice").hasRole("ADMIN")
.anyRequest().authenticated();
// login
http.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll(); // ๋ชจ๋ ํ์ฉ
// logout
http.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/");
}
@Override
public void configure(WebSecurity web) {
// ์ ์ ๋ฆฌ์์ค spring security ๋์์์ ์ ์ธ
// web.ignoring().antMatchers("/images/**", "/css/**"); // ์๋ ์ฝ๋์ ๊ฐ์ ์ฝ๋์
๋๋ค.
web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}
/**
* UserDetailsService ๊ตฌํ
*
* @return UserDetailsService
*/
@Bean
@Override
public UserDetailsService userDetailsService() {
return username -> {
User user = userService.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
};
}
}
728x90