은은하게 코드 뿌시기

스프링 시큐리티 / Spring security 란? 본문

웹/Spring Boot

스프링 시큐리티 / Spring security 란?

은은하게미친자 2023. 4. 18. 16:10
728x90

1. 스프링 시큐리티 (Spring security)  : 기능

 

스프링 시큐리티는 스프링 기반의 보안 프레임워크입니다. 스프링 시큐리티를 사용하면 웹 애플리케이션의 보안을 쉽게 구현할 수 있습니다. 스프링 시큐리티는 인증(Authentication)과 권한 부여(Authorization) 기능을 제공합니다.

 

1) 인증(Authentication) 

사용자를 식별 , 사용자가 누구인지 확인하는 과정입니다. 사용자가 제공한 아이디와 비밀번호를 검증하고, 인증된 사용자 정보를 기반으로 애플리케이션에서의 접근 권한을 제어합니다.

2) 인가, 권한 부여(Authorization)

시스템 자원에 대한 접근을 통제, 인증된 사용자가 어떤 동작을 수행할 수 있는지를 결정하는 과정입니다. 인증된 사용자의 권한을 확인하고, 해당 권한에 따라 애플리케이션의 리소스에 접근을 허용하거나 거부합니다.

스프링 시큐리티는 다양한 인증 방식을 지원하며, 폼 로그인(Form Login), OAuth, LDAP 등 다양한 인증 방식을 제공합니다. 또한, 스프링 시큐리티는 애플리케이션의 보안을 강화하는데 매우 유용한 다양한 보안 기능을 제공합니다.

스프링 시큐리티를 사용하면, 보안 기능을 일관성 있게 적용할 수 있으며, 애플리케이션 개발자가 보안 기능을 쉽게 구현할 수 있도록 다양한 기능과 API를 제공합니다. 따라서, 스프링 시큐리티를 사용하면 애플리케이션의 보안을 쉽게 구현하고, 공격에 대한 대응도 보다 강력하게 할 수 있습니다.

 

2. 스프링 시큐리티 (Spring security)   : 구성요소

 

스프링 시큐리티는 서블릿 필터의 집합입니다.

서블릿 피터는 디스패처 서블릿 실행전 실행되는 클래스인데요. 스프링 시큐리티도 동일한 개념입니다.

API가 실행 되기 전에 스프링 시큐리티가 실행되고 그떄 사용자 인증 처리를 합니다.

 

서블릿을 사용할 때와 다른점이라면, web.xml 대신 WebSecurityConfigurerAdapter 클래스를 사용합니다. 또한 Http Filter를 상속했던 서블릿과 다르게 대부분의 필터에 OncePerRequestFilter를 상속합니다.

 

 

스프링 흐름도 참고 :

https://leggo.tistory.com/117

 

spring 상세 구조, 흐름도

내가 한땀한땀 그린거임. 어디 가져갈꺼면 댓글점 1. 클라이언트 URL을 통한 정보요청 2,3. 뷰 의 데이터를 필터처리 : web.xml 처리한 데이터 가Front Cotroller에 전달 4,5. 서블릿 Handler Mapping 에서 @reques

leggo.tistory.com

 

3. 시큐리티 적용해보기 - 

1) 시큐리티 -  기본설정 만하기 

기본설정 관련 참고 :

https://leggo.tistory.com/207

 

스프링 시큐리티 기본 설정 / springsecurity 기초

스프링 시큐리티 를 설정한 프로젝트를 로컬에서 돌리면 메인 페이지가 뜨는게 아니고 아래 사진처럼 난 이런거 만든적없는데 하는 페이지가 뜬다.. 왤까? 아이디는 머고.. 비밀번호는 뭘쓰라는

leggo.tistory.com

2) WebSecurityConfigurerAdapter  - 시큐리티 설정 파일 작성하기...

  • @EnableWebSecurity  : 이 클래스로부터 생성된 객체가 시큐리티 설정파일 임을 의미
  • @EnableWebSecurity  애노테이션을 WebSecurityConfigurerAdapter 를 상속하는 설정 객체에 붙여주면 SpringSecurityFilterChain 에 등록된다.
  • WebSecurityConfigurerAdapter 의 configure() 메소드를 재정의해서 시큐리티의 설정을 커스터마이징할 수있다.
    • configure() 메소드는 HttpSecurity 객체를 매개변수로 받는데, 이 HttpSecurity 객체를 이용하여 애플리케이션 자언에 대한 인증과 인가를 제어 할 수있다.
    • WebSecurityConfigurerAdapter 클래스를 상속한 시큐리티 설정 클래스가 빈으로 등록되기만 해도(별도의 구현을 안하고 상속만 받은 클래스를 구현할 경우) 이제 더 이상 애플리케이션에서는 로그인을 강제하지 않는다.
    • WebSecurityConfigurerAdapter 클래스 를 재정의 해서 사용 함으로서  
    • 사용자 인증정보를 설정하고 URL 에 따른 접근권한 설정 (특정URL에 만 권한을 설정하거나, 특정 권한을 가진 사용자만 접근할 수 있또록 설정),보안설정,로그인 설정(로그인페이지설정, 로그인 성공 후 이동할 URL 설정),
    • 로그아웃 설정 등 다양한 커스터마이징을 구현 할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private CustomUserDetailsService customUserDetailsService;
 
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
 
    }
 
}
 
cs

 

+  시큐리티 커스터마이징의 예로 다양한 경로에 대한 인증과 인가 하여 처리 할 수 있다.

요청 URL 의미
/ 인증을 하지 않은 모든 사용자가 접근할 수 있다.
/member 인증을 통과한 사용자만 접근할 수있다.
/manager 인증을 통과했고, MANAGER 권한을 가진 사용자만 접근할 수있다.
/admin 인증을 통과했고, ADMIN 권한을 가진 사용자만 접근할 수 있다.

 

WebSecurityConfigurerAdapter   의 자세한 설명 참조 : 

https://leggo.tistory.com/212

 

스프링 시큐리티 - WebSecurityConfigurerAdapter / HttpSecurity

1) WebSecurityConfigurerAdapter 클래스 : Spring Security에서 제공하는 클래스 중 하나로, 웹 보안 설정을 구성하는 데 사용됩니다. 이 클래스를 상속받아서 구현한 자바 설정 클래스에서는 configure() 메서드

leggo.tistory.com

 

 

3) 시큐리티 필터 / 시큐리티 동작원리

스프링 시큐리티는 다양한 필터체인을 제공한다. 

자세한 내용은 아래 포스팅 참고

 

https://leggo.tistory.com/213

 

springsecurity - securityFilter/시큐리티필터

1. 시큐리티필터 스프링시큐리티는 서블릿 필터로 개발한 시큐리티 필터에 대한 이해에서 출발한다. 서블릿 필터는 클라이언트의 요청을 가로채서 서블릿이 수행되기 전후에 전처리 후처리를

leggo.tistory.com

 

4) DB 연동하기

1. 의존성추가 pom.xml  - spring boot기반..

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. 데이터베이스 설정

application.properties 파일에 데이터베이스 정보와 테이블 생성 쿼리를 작성합니다. 

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.initialization-mode=always
spring.datasource.schema=classpath:/schema.sql
schema.sql 파일에 다음과 같이 테이블 생성 쿼리를 작성합니다.
+ 비밀번호 를 암호화하지 않으려면 {noop} 을 추가해주면된다.
create table users (
    username varchar(50) not null primary key,
    password varchar(255) not null,
    enabled boolean not null
);

create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    constraint fk_authorities_users foreign key(username) references users(username)
);
Spring Security에서 사용자 정보를 인증하기 위해, DB 의 username과 password의 컬럼명을 맞춰주어야 합니다.

조회한 사용자 정보를 시큐리티에서 내부적으로 사용하는 org.springframework.security.core.userdetails.User 객체에
자동으로 매핑하는데 이때 아이디는"username" 에 비밀번호는 "password " 변수에 각각 저장하는데
조회 결과  데이터베이스의 사용자 정보 테이블에서 컬럼명을 username과 password로 일치하게 지정해 주어야 자동으로 매핑 됩니다.


만약 데이터베이스의 컬럼명이 다르다면, JdbcUserDetailsManager를 상속하여 사용자 정보를 가져오는 DAO 클래스를 직접 구현해야 할 수도 있습니다. 이를 통해 사용자 정보를 가져오는 SQL 쿼리와 매핑되는 DTO 클래스를 작성하고, JdbcTemplate 등의 JDBC Template을 사용하여 데이터베이스와 연동하여 사용자 정보를 가져올 수 있습니다.

3. 스프링 시큐리티 설정

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select username, password, enabled from user where username=?")
            .authoritiesByUsernameQuery("select u.username, r.role from user_roles r, user u where u.username=? and u.id=r.user_id");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
passwordEncoder () 메소드는 패스워드 인코더를 설정합니다.
Bcrypt 알고리즘 인코더를 사용하였습니다.

참고 포스팅 :

https://velog.io/@parkirae/Spring-Security-%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80%EC%9A%94

 

[Spring Security] 스프링 시큐리티란 무엇인가요?

스프링 시큐리티란 무엇인가요?

velog.io

https://catsbi.oopy.io/c0a4f395-24b2-44e5-8eeb-275d19e2a536

 

스프링 시큐리티 기본 API및 Filter 이해

목차

catsbi.oopy.io

 

728x90
Comments