728x90
1. 의존성 추가
- build.gradle 에 다음 의존성을 추가해준다.
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'
- Maven의 경우 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>
2. 시큐어Configure 파일을 생성해서 다음의 코드를 작성해준다.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests()
.antMatchers("/css/**").permitAll()
.antMatchers("/board/**").authenticated()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") // 권한 설정
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/loginForm") // 로그인 페이지
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.permitAll();
}
}
- @EnableWebSecurity : 스프링 시큐리티 필터가 스프링 필터체인에 등록된다.
- BCryptPasswordEncoder : 유저의 패스워드를 암호화하는 인코더
- authorizeRequests() : 시큐리티 처리에 HttpServletRequest를 이용하겠다는 의미
- antMatchers() : 특정 경로 지정
- permitAll() : 접근 허용
- authenticated() : authorizeRequests에 적힌 경로는 로그인 후에 접근 가능
- access : 주어진 SpEL표현식의 결과가 true이면 접근 허용
- hasRole('ROLE_ADMIN') : 권한이 ROLE_ADMIN인 경우만 접근 가능
- anyRequest().permitAll() : 그 외 요청은 허용
- loginProcessingUrl("/login") : 시큐리티에서 로그인을 대신 진행하도록 정의 -> 컨트롤러에 안만들어도 됨.
3. 비밀번호 인코딩
@PostMapping("/join")
public String join(Member member){ // view의 form->input 의 name과 매핑됨.
String encPwd = bCryptPasswordEncoder.encode(member.getPassword());
member.setPassword(encPwd);
memberService.join(member);
return "redirect:/loginForm";
}
- 컨트롤러에서 BCryptPasswordEncoder 객체를 이용해서 encode 함수를 통해 인코딩 한다.
-
* 해당 글은 인프런에 게시된 '최주호'님의 강의를 듣고 개인적으로 정리한 글입니다.
'Web > SpringBoot' 카테고리의 다른 글
[Spring Boot] 3. Spring Security 권한 설정 (0) | 2021.12.17 |
---|---|
[Spring Boot] 2. Spring Security 로그인 (0) | 2021.12.17 |
[Spring Boot] Entity, DTO, VO 정의 (0) | 2021.12.17 |
[Spring Boot] JPA defalut 값 설정하기 (@DynamicInsert, @DynamicUpdate) (0) | 2021.12.17 |
[Spring Boot] Auto Increment (@GeneratedValue) (0) | 2021.12.16 |