spring-project

Spring Security Multiple HttpSecurity(Form Login & Http Login)

가는가래 2020. 1. 19. 01:15

하나의 프로젝트에서 폼로그인도 되고 Http Login도 되도록 설정을 하려면 다음과 같이 설정을 변경해 주면 된다.

 

Reference 참조

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity

 

Spring Security Reference

The authenticator is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read them

docs.spring.io

 

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {

@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

@Autowired
UserService userService;

protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated().and().httpBasic();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}

@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

@Autowired
UserService userService;


@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests() //
.antMatchers("/", "/main").permitAll().antMatchers("/static/**").permitAll() //
.antMatchers("/img/**", "/js/**", "/css/**", "/fonts/**").permitAll() //
.antMatchers("/member/join", "/member/register").permitAll() //
.anyRequest().authenticated() //
.and() //
.formLogin() //
.loginPage("/login") //
.loginProcessingUrl("/login_process") //
.usernameParameter("id") //
.passwordParameter("pw") //
.defaultSuccessUrl("/main", true) //
.failureUrl("/login?error=true").permitAll().and() //
.logout() //
.logoutSuccessUrl("/main") //
.permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}

}