
lombok, spring security, jpa, spring web, h2 database, validation 추가

lombok- Enable annotation processing 체크
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")ResponseEntity<String> hello(){
return ResponseEntity.ok("hello");
}
}
401 Unauthorized Error를 볼 수 있다.
이를 해결하기 위해서는 Security 설정을 해줘야하는데 다음과 같다.
/*
1) @EnableWebSecurity - 기본적인 Web 보안 활성화
2) WebSecurityConfigurer implements - 추가적인 설정을 하고자 할때
3) WebSecurityConfigurerAdapter extends - deprecated 됐다. 다른 방식 사용
* */
@EnableWebSecurity//기본적인 Web 보안을 활성화 하겠다.
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()//HttpServletRequest 를 사용하는 요청들에 대한 접근제한을 설정하겠다.
.antMatchers("/api/hello").permitAll()// "/api/hello"에 대한 요청은 인증없이 접근을 허용하겠다.
.anyRequest().authenticated();//나머지 요청에 대해서는 모두 인증을 받아야한다.
}
}
WebSecurityConfigurerAdapter는 Spring Security 5.0부터 deprecated 되었다.
대신WebSecurityConfigurerAdapter를 확장한WebSecurityConfigurer를 사용하거나SecurityFilterChain사용하여 구현이 가능하다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http)throws Exception {
http
.authorizeRequests((auth)->auth
.antMatchers("/api/hello").permitAll().anyRequest().authenticated())
.httpBasic();
return http.build();
}
}

H2 DB 사용, 메모리 저장
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:jwttutorial
driver-class-name: org.h2.Driver
username: sa
password:
//create-drop의 의미
//sessionFactory 시작될때 - (Drop,Create,Alter) 종료시 - Drop
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
show_sql: true
logging:
level:
com.studyjwt: DEBUG