Spring

[youtube] Spring-Security

com_0 2023. 4. 25. 14:52

유튜브 영상을 보면서 spring security를 조금 활용하는 공부를 해 보았는데, 기억할만한 부분들 정리

 

spring 참고링크 : https://spring.io/guides

 

Spring | Home

Cloud Your code, any cloud—we’ve got you covered. Connect and scale your services, whatever your platform.

spring.io

thymeleaf 참고링크 : https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

bootstrap 참고링크 : https://getbootstrap.com/docs/4.5/getting-started/introduction/

 

Introduction

Get started with Bootstrap, the world’s most popular framework for building responsive, mobile-first sites, with jsDelivr and a template starter page.

getbootstrap.com

 

WebSecurityConfig.java

- csrf (cross-site request forgery)

사이트간 요청 위조의 줄임말 웹 애플리케이션 취약점 중 하나로 사용자가 자신의 의지와 무관하게 공격자가 의도한 행동을 해서 특정 웹페이지를 보안에 취약하게 한다거나 수정, 삭제 등의 작업을 하게 만드는 공격 방법이다.

예방 방법 : 패스워드 변경 같은 민감한 정보를 다룰 때에는 세션에 토큰을 발급해서, 해당 토큰이 없는 상황에서 해당 동작들이 이루어지면 요청을 거부하는 방법을 통하여 사용자가 정말로 변경을 의도하는 경우에만 변경을 시켜주는 방법 / 변경 시에 CAPTCHA (웹사이트에서 사람이 접근하려고 하는 것인지 이 접근하는 것인지 판단하기 위하여 사용되는 튜링 테스트) 를 이용하여 CAPTCHA 인증코드가 없거나 틀리면 거부하도록 하는 방법 등이 이용되고 있다.

spring security에서는 @EnableWebSecurity 어노테이션이 기본적으로 csrf 공격을 방지하는 기능을 가지고 있다.

ex) http.csrf().disable()

- antMatchers

특정 URL에 특정 권한을 가진 사용자만 접근 가능하도록 설정하는 spring security 명령어

@EnableWebSecurity
public class BrmsWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login**", "/web-resources/**", "/actuator/**").permitAll()
                .antMatchers("/admin/**").hasAnyRole("ADMIN")
                .antMatchers("/order/**").hasAnyRole("USER")
                .anyRequest().authenticated();
    }
}

.permitAll() : 모든 사용자에게 접근 허가

.hasAnyRole("ADMIN") : "ADMIN" 권한을 가진 사용자에게 접근 허가

.hasAnyRole("USER") : "USER" 권한을 가진 사용자에게 접근 허가

- passwordEncoder()

비밀번호를 평문 그대로 데이터베이스에 저장해두면, 해커에게 정보가 금방 노출되기 때문에 비밀번호는 항상 암호화 해서 데이터베이스에 저장해주어야 한다.

@Bean
public PasswordEncoder getPasswordEncoder() {
  return new BCryptPasswordEncoder();
}

BCryt 방식을 이용해 암호화를 진행하는 인코더 -> @Bean 어노테이션 주입이 되어 있기 때문에 활용하기 위해서 class에 @Configuration 어노테이션이 필요하다.

 

 

Model

- cascade

엔티티의 상태변화를 전파시키는 옵션으로 CascadeType.ALL / CascadeType.PERSIST / CascadeType.MERGE / CascadeType.REMOVE / CascadeType.REFRESH / Cascade.DETACH 가 있다.

@OneToMany나, @ManyToOne 옵션을 사용했을 경우, 상위 엔티티에서 발생하는 변화를 하위 엔티티까지 전파시키고자할 때 사용합니다.

- orphanRemoval

@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, orphanRemoval = true)

자식 엔티티의 변경이 있다면 JPA 에서 자식엔티티의 수정은 insert update delete 순으로 이어지는데, 변경된 자식을 먼저 insert 하고

기존의 자식을 NULL로 update 한다.

그리고 orphanRemoval 옵션을 true 로 하면 기존 NULL처리된 자식을 DELETE 한다.  PK(JoinColumn)값이 NULL로 변한 자식은 고아객체라고 하여 연결된 점이 없는 객체이다.  orphanRemoval옵션은 바로 이 고아객체를 삭제해주는 역활을 한다.

- FetchType

  • fetch : 쭉 벋은 어딘가에 있는 것을 가져오기
  • @XXXToOne : default 값이 즉시 로딩 (FetchType.EAGER) 으로 프로그램이 돌아갈 때 불필요한 데이터를 모두 불러오면서 성능 문제를 발생시킬 수 있다.
  • @OneToMany & @ManyToMany : default 값이 지연 (FetchType.LAZY) 으로 설정되어 있다.

 

Repository

- @EntityGragh ( attributePath = {"boards"} )

  • FetchType.LAZY 설정 시 메인엔티티만 조회 후 자식 엔티티는 proxy 객체가 대체되어 대입되는데, 그 후 해당 proxy 객체를 호출할 때마다 그때 그때 select 쿼리를 실행한다.
  • 이 때 fetch 조인을 사용해 여러번의 쿼리 실행을 한번에 해결 가능합니다 (이 기능을 가능하게 만든 어노테이션)

- querydsl

  • @Query ( "select p from Post p join fetch p.user u" + "where u in" + "(select t from Follow f innner join f.target ~~~
  • 코드로 쿼리 작성해서 컴파일 시점에 문법 오류를 쉽게 확인 가능
  • 동적 쿼리 작성에 편리

 

Application.properties

- logging.level.org.hibernate.SQL=DEBUG

- logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE (sql 명령어 확인 가능)