React - 10(Spring Security)

월요일좋아·2023년 1월 18일
0

React

목록 보기
8/11

프로젝트 생성

스프링 공식 사이트
https://spring.io/projects/spring-boot#support

스프링 버전 수정

build.gradle에서 2.7.7 -> 2.6.14 로 버전 수정하기

초기설정

처음에 실행하면 오류나는 것 : DB연결문제 -> 아래 코드대로 build.gradle 주석처리

스프링 시큐리티

https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security

dependency 추가

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
    implementation 'org.springframework.boot:spring-boot-starter-security'

localhost:8080/login

id : user, pw : 콘솔에 출력된 security password

로그인 성공 후 다른 페이지를 볼 수 있음

로그아웃 : localhost:8080/logout

configuration

스프링 시큐리티를 사용하기 위해서는 configuration 을 하나 만들어야 한다.

2.7.x 버전부터는 사용법이 조금 달라짐.

WebSecurityConfigurerAdapter 상속

스프링 시큐리티 설정을 위해서 WebSecurityConfigurerAdapter 클래스를 상속받아 사용함 (2.6.x 버전까지)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	...
}

비밀번호 암호화

스프링 시큐리티에서는 반드시 비밀번호를 암호화해서 사용해야 함
BCryptPasswordEncoder 클래스를 사용하여 비밀번호를 암호화 함
@Bean 추가

  @Bean
  PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

HttpSecurity 클래스

스프링 시큐리티를 사용하는 웹 페이지에 접속할 경우 필요한 설정을 할 수 있음
인증과 인가에 관련된 API 를 제공하는 클래스이다.

기능

필요한 설정을 진행

authorizeRequests() : 요청에 대한 보안 설정을 시작하는 메서드
authorizeHttpRequests() : http 요청에 대한 보안 설정을 시작하는 메서드
antMatchers(url) : 지정한 주소에 대한 url 주소에 대한 설정
permitAll() : 지정한 url 에 대해서 사용 인가
hasRole(권한등급) : 지정한 등급의 사용자만 지정한 url 에 대하여 사용 인가
hasAnyRole(권한등급) : 지정한 url 에 대하여 지정한 등급 중 하나 이상을 가진 사용자만 접근 가능
isAnonymous() : 익명 사용자만 접근
isRememberMe() : Remember Me 인증을 통해서 접근 시에만 인가
isFullyAuthenticated() : Remember Me 가 아닌 일반적인 인증 방법으로 로그인 시에만 접근
denyAll() : 접근 불가
principal() : 인증된 사용자의 사용자 정보 반환(UserDetails 인터페이스를 구현한 클래스의 객체) (잘 안씀)
authentication() : 인증된 사용자의 인증 정보 반환(Authentication** 인터페이스를 구현한 클래스의 객체) (잘 안씀)
formLogin() : 기본 스프링 시큐리티 로그인 페이지 사용

로그인 페이지 사용 시 사용할 수 있는 추가 옵션

loginPage(url) : 사용자 정의 로그인 페이지 지정
defaultSuccessUrl(url) : 로그인 성공 후 이동할 페이지 지정
failureUrl(url) : 로그인 실패 후 이동할 페이지 지정
usernameParameter(ID) : ID 파라미터명 설정
passwordParameter(PW) : 비밀번호 파라미터명 설정
loginProcessingUrl(url) : 로그인 Form Action Url 지정
successHandler(loginSuccessHandler()) : 로그인 성공 후 동작할 내용 설정
failureHandler(loginFailureHandler()) : 로그인 실패 후 동작할 내용 설정
logout() : 로그아웃 기능 활성화, 기본적으로 로그아웃 페이지는 POST 방식으로만 동작함

로그아웃 페이지 사용 시 사용할 수 있는 추가 옵션

logoutUrl(url) : 로그아웃 처리 페이지 지정
logoutSuccessUrl(url) : 로그아웃 성공 시 이동할 페이지 지정
deleteCookies("JSESSIONID", "remember-me") : 로그아웃 시 쿠키 삭제
addLogoutHandler(addLogoutHandler()) : 로그아웃 시 동작할 내용 설정
logoutSuccessHandler(logoutSuccessHandler()) : 로그아웃 성공 시 동작할 내용 설정

securityConfig.java

package com.bitc.securitytest.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


// 스프링 시큐리티 설정을 위해서 WebSecurityConfigurerAdapter 클래스를 상속받아 사용함 (2.6.x 버전까지)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  // 스프링 시큐리티에서는 반드시 비밀번호를 암호화해서 사용해야 함
  // BCryptPasswordEncoder 클래스를 사용하여 비밀번호를 암호화 함
  @Bean
  PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  // HttpSecurity 클래스 : 스프링 시큐리티를 사용하는 웹 페이지에 접속할 경우 필요한 설정을 할 수 있음
  // 인증과 인가에 관련된 API 를 제공하는 클래스

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // 필요한 설정을 진행
    // authorizeRequests() : 요청에 대한 보안 설정을 시작하는 메서드
    // authorizeHttpRequests() : http 요청에 대한 보안 설정을 시작하는 메서드
    //★ antMatchers(url) : 지정한 주소에 대한 url 주소에 대한 설정
    //★ permitAll() : 지정한 url 에 대해서 사용 인가
    //★ hasRole(권한등급) : 지정한 등급의 사용자만 지정한 url 에 대하여 사용 인가
    //★ hasAnyRole(권한등급) : 지정한 url 에 대하여 지정한 등급 중 하나 이상을 가진 사용자만 접근 가능
    // isAnonymous() : 익명 사용자만 접근
    // isRememberMe() : Remember Me 인증을 통해서 접근 시에만 인가
    // isFullyAuthenticated() : Remember Me 가 아닌 일반적인 인증 방법으로 로그인 시에만 접근
    // denyAll() : 접근 불가
    // principal() : 인증된 사용자의 사용자 정보 반환(UserDetails 인터페이스를 구현한 클래스의 객체) (잘 안씀)
    // authentication() : 인증된 사용자의 인증 정보 반환(Authentication** 인터페이스를 구현한 클래스의 객체) (잘 안씀)
    http.authorizeRequests()
        // 보안인증 시작 → "sec/all" 경로에 대해서는 인증 open 하겠다.
        .antMatchers("/sec/all").permitAll() // 여기까지 쓰면 모든 페이지 접근 가능
//        .antMatchers("/sec/member").hasRole("USER")  // 여기까지 쓰면 member 접속 안됨, all 은 정상적으로 뜸, login/logout 안됨
        .antMatchers("/sec/member").hasAnyRole("ADMIN", "USER")
        .antMatchers("/sec/admin").hasRole("ADMIN");  // http.logout(); 이후 추가 코드

    // formLogin() : 기본 스프링 시큐리티 로그인 페이지 사용
    // 로그인 페이지 사용 시 사용할 수 있는 추가 옵션
    // loginPage(url) : 사용자 정의 로그인 페이지 지정
    // defaultSuccessUrl(url) : 로그인 성공 후 이동할 페이지 지정
    // failureUrl(url) : 로그인 실패 후 이동할 페이지 지정
    // usernameParameter(ID) : ID 파라미터명 설정
    // passwordParameter(PW) : 비밀번호 파라미터명 설정
    // loginProcessingUrl(url) : 로그인 Form Action Url 지정
    // successHandler(loginSuccessHandler()) : 로그인 성공 후 동작할 내용 설정
    // failureHandler(loginFailureHandler()) : 로그인 실패 후 동작할 내용 설정
    http.formLogin();
    // logout() : 로그아웃 기능 활성화, 기본적으로 로그아웃 페이지는 POST 방식으로만 동작함
    // 로그아웃 페이지 사용 시 사용할 수 있는 추가 옵션
    // logoutUrl(url) : 로그아웃 처리 페이지 지정
    // logoutSuccessUrl(url) : 로그아웃 성공 시 이동할 페이지 지정
    // deleteCookies("JSESSIONID", "remember-me") : 로그아웃 시 쿠키 삭제
    // addLogoutHandler(addLogoutHandler()) : 로그아웃 시 동작할 내용 설정
    // logoutSuccessHandler(logoutSuccessHandler()) : 로그아웃 성공 시 동작할 내용 설정
    http.logout();
    // 실행 -> sec/member 접속 시 바로 /login 페이지로 이동됨
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user1").password(passwordEncoder().encode("1111")).roles("USER");
    auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("1111")).roles("ADMIN");
  }
}

0개의 댓글