스프링 시큐리티 세팅
스프링 시큐리티를 프로젝트에 작동시키면
(pom.xml 에 시큐리티 의존성 설정되어 있으면 작동)
내가 만드는 프로젝트에는 아래와 같은 의존성 설정했음
<pom.xml> 파일
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
우리가 만드는 웹 사이트 어느 페이지로 이동하던지.
로그인 화면이 뜨게 된다.
이렇게 로그인을 해야만 요청하는 페이지로 이동이 가능하다.
아마, username, password에 입력해야 하는 값이 이클립스(sts) 콘솔창에 나오는 것으로 알고 있다.
그 값을 찾아서 입력하면 된다.
그런데, 우리가 직접 로그인 화면을 만들어
로그인 처리를 진행하려면
WebSecurityConfigurerAdapter 를 상속해서 여러 처리를 해야 한다.
그래서 아래와 같이 만들었다.
<SecurityConfig.java> 파일
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
public BCryptPasswordEncoder encode() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/", "/user/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/auth/signin") // GET
.loginProcessingUrl("/auth/signin") // POST -> 스프링 시큐리티가 로그인 프로세스 진행
.defaultSuccessUrl("/");
}
}
위에서 보이는 이 코드는
@Bean
public BCryptPasswordEncoder encode() {
return new BCryptPasswordEncoder();
}
비밀번호 해쉬화에 필요한 객체(BCryptPasswordEncoder)를 만드는 코드이다.
이 아래에 있는 코드를 보면
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); //csrf 토큰 비활성화
http.authorizeRequests() // HttpServletRequest 요청 URL에 따라 접근 권한 설정
.antMatchers("/", "/user/**").authenticated()
// 만약 /, /user 로 시작되는 요청이 있다면,
// 인증이 필요함
.anyRequest().permitAll()
// 그 외의 다른 요청들은 인증 필요 없이 허용함
.and()
// 그리고
.formLogin()
// form 로그인을 진행(위의 antMatchers 주소로 요청이 오면 자동으로 로그인화면 이동)
.loginPage("/auth/signin") // GET
// /auth/signin.jsp 파일에 로그인화면 구현했음
// 그래서 이리로 (우리가 만든 로그인 화면) 이동되도록
.loginProcessingUrl("/auth/signin") // POST -> 스프링 시큐리티가 로그인 프로세스 진행
.defaultSuccessUrl("/");
// 정상적으로 모두 완료되면 / 이 주소로 이동
}
<1> 로그인 처리
.antMatchers("/", "/user/**").authenticated()
-> 만약 / , /user 요청이 오면
.formLogin()
-> form 로그인 할거임(jsp 에서 form 태그)
.loginPage("/auth/signin")
-> /auth/signin 으로 이동해서 로그인 함
.defaultSuccessUrl("/");
-> 모두 완료 되면 / 이 주소로 이동
<2> 로그인 안 함
.anyRequest().permitAll()
-> /, /user 가 아닌 다른 주소들은 로그인 필요없이
.defaultSuccessUrl("/");
-> / 주소로 이동
그래서,만약 웹사이트에서
/user 이런식으로 요청을 보내면
f12 , network 창에 보면
이렇게
user 요청시 상태 정보가 302 로 되어 있는 것을 알 수 있다.
그리고 바로 signin 주소로 이동되었음을 알 수 있는데 여기서는 200 이다.
http 상태 정보를 보면
302 번은, 요청한 주소의 URL 이 일시적으로 변경되었음을 뜻하고,
200번은 요청이 성공적으로 되었음을 알려준다.
참고자료 :
https://developer.mozilla.org/ko/docs/Web/HTTP/Status
HTTP 상태 코드 - HTTP | MDN
HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 알려줍니다. 응답은 5개의 그룹으로 나누어집니다: 정보를 제공하는 응답, 성공적인 응답, 리다이렉트, 클라이언트 에러, 그리고
developer.mozilla.org
즉, /user 로 요청했지만, 바로 /signin으로 이동된 것이다.
그래서 이런식으로 우리가 만든 로그인 창이 화면에 나오게 된다 (/auth/signin)
(로그인 창은 /auth 주소 아래 signin.jsp 파일로 만들었다.)
<signin.jsp> 파일
<form class="login__input" action="/auth/signin" method="POST">
<input type="text" name="username" placeholder="유저네임" required="required" />
<input type="password" name="password" placeholder="비밀번호" required="required" />
<button>로그인</button>
</form>
스프링 시큐리티 세팅 참고 자료 : https://bamdule.tistory.com/53
[Spring Boot] Spring Security 적용하기
Spring Security 란? Spring Security는 스프링 기반의 어플리케이션 보안을 담당하는 프레임워크입니다. Spring Security를 사용하면 사용자 인증, 권한, 보안처리를 간단하지만 강력하게 구현 할 수 있습니
bamdule.tistory.com
참고 자료 : 이지업 강의 사이트 " 스프링부트 SNS프로젝트 - 포토그램 만들기"