스프링에서 제공하는 기본 로그인 화면을 커스터마이징 하지 않고 그대로 사용하기에는 부족하다.
아이디와 비밀번호를 받아와 로그인 하는 기능은 할 수 있지만, 실제로 로그인에서 이 기능만 하지는 않는다.
그렇기 때문에 우리는 내가 원하는 로그인 화면을 Spring Security 로그인에 맞게 커스터 마이징 해서 사용해야 한다.
Spring Boot + Security + Gradle을 사용한 로그인/로그아웃을 구현 시 어떻게 Spring Security 커스터 마이징 하는지 간단하게 알아보자.
의존성 추가
📁 Build.gradle
implementation 'org.springframework.boot:spring-boot-starter-security' //spring security
implementation 'org.springframework.security:spring-security-test'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' //thymeleaf
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' //thymeleaf integration
타임리프 관련 의존성을 추가하지 않으면 security 태그 sec을 사용할 수 없다.
Security 설정
📂 config/WebSecurityConfig
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll() //인증 없이 접근 가능
.anyRequest().authenticated() //인증 해야 접근 가능
.and()
.formLogin()
.loginPage("/account/login") // 로그인 페이지 지정
.usernameParameter("email")
.permitAll()
.and()
.logout()
.permitAll();
}
// Spring Security의 AuthenticationManagerBuilder를 사용해 jdbc 인증처리
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.passwordEncoder(passwordEncoder()) // 스프링에서 인증처리 할 때 passwordEncoder를 통해 비밀번호 암호화를 알아서 진행
.dataSource(dataSource) // 현재 동작하는 데이터소스를 가져옴
.usersByUsernameQuery("select email, password, enabled " // 인증(로그인)처리를 위한 쿼리문
+ "from user "
+ "where email = ?")
.authoritiesByUsernameQuery("select u.email, r.authority " // 권한 처리를 위한 쿼리문
+ "from user_role ur inner join user u on ur.user_id = u.id "
+ "inner join role r on ur.role_id = r.id "
+ "where u.email = ?");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
- WebSecurityConfigurerAdapter 상속
- configure(WebSecurity web) 구현
- configure(HttpSercurity http) 구현
- HttpSecurity : http request에 대한 보안 설정
- authorizeRequests() : request에 따라 접근 제어
- anMatchers().permitAll() : 인증 없이 접근 가능
- anyRequest().authenticated() : 그 이외 모든 요청은 인증을 해야 접근 가능
- formlogin() : form 로그인 기반으로 인증 설정
- loginPage() : 로그인 페이지
- usernameParameter() : 커스텀 파라미터 (default=username)
- passwordParameter() : 커스텀 파라미터 (default=password)
- defaultSuccessUrl() : 로그인 성공시 가게 될 페이지
- failureUrl() : 로그인 실패시 가게될 페이지
- successHandler() : 로그인 성공 이후 호출되는 함수
- failureHandler() : 로그인 실패 이후 호출되는 함수
- authorizeRequests() : request에 따라 접근 제어
스프링 시큐리티는 기본적으로 로그인 폼에서 input태그의 name 속성값으로 username과 password를 defalt값으로 사용한다. 따라서 이 속성 값들을 원하는 대로 변경할 경우 반드시 usernameParameter(), passwordParameter()를 통해 Spring Security 설정을 변경해줘야 한다!
이것때문에 삽질을 꽤 했기에... 꼭 기억하자..
Reference
spring Security - 로그인 화면 커스터마이징
spring boot + gradle + security를 이용한 로그인/로그아웃 구현
securing a Web Application - spring io
'🌱 Spring > Security' 카테고리의 다른 글
[security] spring security를 이용해 인증처리 하기 (1) | 2022.09.20 |
---|---|
[security] 사용자 권한 thymeleaf 연결하기 (0) | 2022.07.14 |