신기하게도 security 를 쓰고 로그인 페이지에서 로그인을 한 뒤에 새로고침을 해도 다시 로그인을 요구하지 않는다.
어떻게 그게 가능한 걸까? 그건 session 과 cookie 때문이다.
이는 postman 에서도 똑같이 작동한다.
Authorized 요청과 Unauthorized 요청에 대한 응답은 쿠키가 다르다.
application.properties 파일에
spring.security.user.name=name
spring.security.user.password=1234
식으로 관리할 수 있지만, 그럴경우 다수의 user 를 관리할 수 없기 때문에 아래의 방법이 필요함.
아래의 방법에서 비밀번호 암호화를 하고 있지 않음.
@EnableWebSecurity
@Configuration
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/myAccount", "/myBalance", "/myLoans" ,"/myCards" ).authenticated()
.antMatchers("/notices", "/contact").permitAll()
.and().formLogin()
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("name").password("1234").authorities("admin")
.and()
.withUser("user").password("1234").authorities("admin")
.and()
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
위의 유저 관리 방법을 이렇게 바꿀 수 있음.
하지만 이런 방식으로 하게되면 password 를 암호화하는 방식(비록 암호화하지 않을지다로)이 지정되지 않아서 오류가 난다.
하지만 PasswordEncoder 를 Bean 으로 만들어서 spring boot container 에 넣어두면 알아서 파악해서 해결해준다.
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
InMemoryUserDetailsManager userDetailService = new InMemoryUserDetailsManager();
UserDetails user = User.withUsername("name").password("1234").authorities("admin").build();
UserDetails user2 = User.withUsername("name").password("1234").authorities("admin").build();
userDetailService.createUser(user);
userDetailService.createUser(user2);
auth.userDetailsService(userDetailService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}