1. 스프링 시큐리티
- 웹 시큐리티
- 메소드 시큐리티
- 다양한 인증 방법 지원
- LDAP, 폼 인증, Basic 인증, OAuth, ...
- 기본적으로 Basic 인증 (Accept 헤더에 TEXT_HTML로 지정할 경우 폼 인증)
2. 스프링 부트 시큐리티 자동 설정
- SecurityAutoConfiguration
: Spring Security가 들어있는 경우에 자동으로 적용되는 설정 파일 - UserDetailsServiceAutoConfiguration
: Spring Boot application이 뜰 때, 기본 사용자 생성 - spring-boot-starter-security
- 모든 요청에 인증 필요
- 인증 관련 각종 이벤트 발생
- DefaultAuthenticationEventPublisher 빈 등록
- 다양한 인증 에러 핸들러 등록 가능 - 기본 사용자 생성
- Username: user
- Password: application을 실행할 때마다 랜덤 값 생성 (콘솔에 출력 됨.)
- spring.security.user.name
- spring.security.user.password
루트를 요청해도 인증정보가 없기 때문에 Spring Security에서 만든 로그인 폼 페이지가 보여짐
3. 의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
-> Spring Security의 경우 모든 요청에 인증이 필요하기 때문에 의존성 추가 전에는 pass되던 테스트가 깨질 수 있음
-> Basic 인증 / Error message : Unauthorized
# 해결 방법
spring-security-test 의존성 추가 및
@WithMockUser 어노테이션을 클래스 또는 메소드마다 추가(가짜 유저 인증정보를 추가해서 테스트 실행)
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${spring-security.version}</version>
<scope>test</scope>
</dependency>
@Test
@WithMockUser
public void hello() throws Exception {
mockMvc.perform(get("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("hello"));
}
# 폼 인증
@Test
public void hello() throws Exception {
mockMvc.perform(get("/hello")
.accept(MediaType.TEXT_HTML))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("hello"));
}
-> 위의 Basic 인증과 다른 결과
# HomeController
@Controller
public class HomeController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/my")
public String my() {
return "my";
}
}
# HomeControllerTest
@RunWith(SpringRunner.class)
@WebMvcTest(HomeController.class)
public class HomeControllerTest {
@Autowired
MockMvc mockMvc;
@Test
@WithMockUser
public void hello() throws Exception {
mockMvc.perform(get("/hello")
.accept(MediaType.TEXT_HTML))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("hello"));
}
@Test
public void hello_without_user() throws Exception {
mockMvc.perform(get("/hello"))
.andDo(print())
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser
public void my() throws Exception {
mockMvc.perform(get("/my"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("my"));
}
}
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard
스프링 부트 개념과 활용 - 인프런 | 강의
스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...
www.inflearn.com
'Java > Spring Boot' 카테고리의 다른 글
[Spring Boot] REST Client (RestTemplate과 WebClient) (0) | 2022.05.07 |
---|---|
[Spring Boot] Spring Security 설정 커스터마이징 (0) | 2022.05.01 |
[Spring Boot] Neo4j (0) | 2022.05.01 |
[Spring Boot] Mongo DB (0) | 2022.05.01 |
[Spring Boot] Redis (0) | 2022.04.17 |