[ODOP] 70 일차 - Spring security
![[ODOP] 70 일차 - Spring security](/content/images/size/w1200/2023/08/-----2023-08-01----10.29.26-5.png)
💡
최신 버전에서는 아래의 방식과는 조금 다르게 권한설정을 진행한다.
아래의 설명들은 모두 구버전(2.6.7)을 기준으로 설명하고 있다
아래의 설명들은 모두 구버전(2.6.7)을 기준으로 설명하고 있다
의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
의존성 추가 시 일어나는 일들
- 서버가 기동되면 스프링 시큐리티의 초기화 작업 및 보안 설정이 이루어진다
- 별도의 설정이나 구현을 하지 않아도 기본적인 웹 보안 기능이 현재 시스템에 연동되어 작동함
- 모든 요청은 인증이 되어야 자원에 접근 가능
- 인증 방식을 폼 로그인 방식과 httpBasic 로그인 방식을 제공
- 기본 로그인 페이지 제공
- 기본 계정 한 개 제공 (id :
user
/ password:스프링 시작 시 나오는 시큐리티 비밀번호
)
Security config 설정
WebSecurityConfigurerAdapter
![](https://blog.pollra.com/content/images/2023/08/-----2023-08-06----2.19.18.png)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
- authorizeRequests()
승인 요청들이 들어왔을 때 - anyRequest()
모든 요청에 - authenticated()
인증 프로세스를 진행한다 - and()
return http
- formLogin()
form 인증을 진행한다
.formLogin() 설정 세부
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html") // 사용자 정의 로그인 페이지
.defaultSuccessUrl("/home") // 로그인 성공 후 이동 페이지
.failureUrl("/login.html?error=true") // 로그인 실패 후 이동 페이지
.usernameParameter("username") // 아이디 파라미터명 설정
.passwordParameter("password") // 패스워드 파라미터명 설정
.loginProcessingUrl("/login") // 로그인 Form Action Url
.successHandler(loginSuccessHandler()) // 로그인 성공 후 핸들러
.failureHandler(loginFailureHandler()) // 로그인 실패 후 핸들러
;
}
}
위 configure 함수의 인자로 넘어오는 HttpSecurity 객체를 이용해 인증의 세부사항을 지정해줄 수 있습니다
다만, 위의 설정으로는 문제가 되는 항목이 있습니다
바로 로그인 페이지에 아무도 접근할 수 없다는 것인데, 이건 다음과 같이 처리하여 해결할 수 있습니다
http.formLogin()
.loginPage(“/login.html") // 사용자 정의 로그인 페이지
... // 생략
.permitAll()
;
sucessHandler()
이 핸들러의 경우 로그인이 성공했을 때 성공 정보가 담겨있습니다
![](https://blog.pollra.com/content/images/2023/08/-----2023-08-06----2.24.12.png)