WEB/web 지식

Spring security 정리

일상코더 2022. 11. 28. 06:43

1. 웹의 인증 및 인가

 

    ●  인증(Authentication) : 사용자 신원을 확인하는 행위

           - 회사 출입을 위한 출입증 확인 혹은 생체 정보, 인식 ( 너 누구누구 맞아?)

           - 아이디/패스워드, 각종 인증서

 

    ●  인가(Authorization) : 사용자 권한을 확인하는 행위

           - 주로 역할에 따른 사용 권한 관리 

           - 특정게시판 조회 권한

           - 회사 건물 내 접근 권한 관리 

                 I. 방문자 -> 회의실만 접근 가능

                II. 직원 -> 회의실, 사무실 접근 가능

               III. 관리자 -> 회의실, 사무실, 서버실, 물품보관실 접근 가능

  

2. 쿠키와 세션

      ● HTTP(HyperText Transfer Protocol) : 웹 상에서 데이터에 대한 요청과 응답을 주고 받는 규칙

      ● State(상태) : 클라이언트(사용자) 측 정보

      ● Stateless 

               - HTTP/HTTPS 방식의 통신이 해당

               - 클라이언트의 정보를 서버에 저장하지 않음

               - 서버에 전송되는 요청이 완료되면 즉시 연결 해제되며, 각 요청은 배타저

      ● Stateful 

               - 데이터베이스 서버에 주로 활용되는 방식이며, TCP, FTP, TELNET 통신이 해당

               - 클라이언트의 정보를 서버에 저장함

               - 전화 통화를 하는 것과 같이 요청에 대한 응답이 종료될 때까지 연결을 유지하려고 함

 

쿠키와 세션 모두 HTTP에 상태 정보를 유지(stateful)하기 위해 사용된다.  Stateless한 HTTP 방식의 통신에 Stateful 한 요소를 더해 서버에서 클라이언트를 인지할 수 있게 된 것이다.

 

 

3. 스프링 시큐리티 적용

      ● 스프링 시큐리티 프레임워크 추가

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();
    }
}

      ● 로그인 페이지 요청 처리

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin() // 로그인 기능작동
                .loginPage("/user/login") // 사용자 정의 페이지 경로
                .defaultSuccessUrl("/") // 로그인 성공 시 이동 페이지 경로
                .failureUrl("/user/login?error") // 로그인 실패 시 이동 페이지 경로
                .permitAll();
    }
}

      ● UserController 파일 생성

package com.sparta.intmd01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    // 회원 로그인 페이지
    @GetMapping("/user/login")
    public String login() {
        return "login";
    }

    // 회원 가입 페이지
    @GetMapping("/user/signup")
    public String signup() {
        return "signup";
    }
}

      ● 스프링 시큐리티의 URL 허용 정책 변경 필요 확인

import org.springframework.context.annotation.Bean;
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.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity // 스프링 Security 지원을 가능하게 함
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authz) -> authz
												// image 폴더를 login 없이 허용
                        .antMatchers("/images/**").permitAll()
												// css 폴더를 login 없이 허용
                        .antMatchers("/css/**").permitAll()
                        // 어떤 요청이든 '인증'
                        .anyRequest().authenticated()
                )
                // 로그인 기능 허용
                .formLogin()
                .loginPage("/user/login")
                .defaultSuccessUrl("/")
                .failureUrl("/user/login?error")
                .permitAll()
                .and()
                //로그아웃 기능 허용
                .logout()
                .permitAll();

        return http.build();
    }
}