인증
에 해당하며, 신원에 따라 출입 장소에 접근할 수 있는 권한을 확인하는 것이 인가
이다.1) 쿠키 (클라이언트에 저장)
2) 세션 (서버에 저장)
// 스프링 시큐리티
implementation 'org.springframework.boot:spring-boot-starter-security'
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;
@Configuration // 서버가 기동될 때 설정해주겠다.
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 어떤 요청이든 '인증'이 필요하다.
.anyRequest().authenticated()
.and()
// 단, 로그인 기능은 인증없이 허용
.formLogin()
.defaultSuccessUrl("/")
.permitAll()
.and()
// 단, 로그아웃 기능은 인증없이 허용
.logout()
.permitAll();
}
}
서버 실행
프론트 엔드에서 작업이 완료되어 css, html 파일을 받은 상황)
// image 폴더를 login 없이 허용
.antMatchers("/images/**").permitAll()
// css 폴더를 login 없이 허용
.antMatchers("/css/**").permitAll()
http.csrf()
.ignoringAntMatchers("/user/**");
- 회원 관리 처리 API 전부를 login 없이 허용
http.authorizeRequests()
.antMatchers("/user/**").permitAll()
@Override
public void configure(WebSecurity web) {
// h2-console 사용에 대한 허용 (CSRF, FrameOptions 무시)
web
.ignoring()
.antMatchers("/h2-console/**");
}
@Bean
public BCryptPasswordEncoder encodePassword() {
return new BCryptPasswordEncoder();
}
0. 전체적인 과정:
// 로그인 View 제공 (GET /user/login)
.loginPage("/user/login")
// 로그인 처리 (POST /user/login)
.loginProcessingUrl("/user/login")
// 로그아웃 처리 URL
.logoutUrl("/user/logout")
public class UserDetailsImpl implements UserDetails {
// ...
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority adminAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(adminAuthority);
return authorities;
}
}
// (관리자용) 등록된 모든 상품 목록 조회
@Secured("ROLE_ADMIN")
@GetMapping("/api/admin/products")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@Configuration
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
@EnableGlobalMethodSecurity(securedEnabled = true) // @Secured 어노테이션 활성화
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
UserRoleEnum role = user.getRole();
String authority = role.getAuthority(); //"ROLE_USER" / "ROLE_ADMIN"
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authority);
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(simpleGrantedAuthority);
return authorities;
}
❗❗❗ 이 과정에서 실행 시 DDL 관련 오류가 나타났다❗❗❗
- @Entity 클래스의 이름을 바꿔주거나
- application.properties에 아래 코드를 작성한다 ( SQL 문이 실행될 때, 백틱으로 테이블과 컬럼을 자동으로 감싸줘서 예약어 충돌을 방지할 수 있다.)
spring.jpa.properties.hibernate.globally_quoted_identifiers=true