PROJECT #생성

김형우·2022년 4월 7일
0

New Project

목록 보기
1/12

0. 프로젝트 생성

  • boot_20220406 프로젝트 생성

1. 라이브러리 설치

  • pom.xml
		<!-- security -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

        <!-- redis 세션저장 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
		</dependency>


		<!-- h2 db (개발용)-->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope> <!-- *** 배포시에는 삭제 -->
		</dependency>

		<!-- h2 또는 oracle session -->
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-jdbc</artifactId>
		</dependency>

		<!-- oracle (서비스용)-->
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>

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

		<!-- tomcat (개발용 웹 서버) -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

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

		<!-- devtools -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>

		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

        <!-- spring boot 자동으로 생성되는 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

        <!-- spring boot 테스트 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

2. 환경설정

2-1. application.properties


# 개발용 포트번호
server.port=9090

# 프로젝트, 배포하는 파일명
server.servlet.context-path=/ROOT

# 소스코드 자동감지 후 재시작
spring.devtools.livereload.enabled=true

# view에 해당하는 html 위치
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# h2 db (개발용 DB)
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:D:/java-workspace/boot_20220406/db01;Mode=Oracle;AUTO_RECONNECT=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

# oracle (서비스용 DB)
# spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# spring.datasource.url=jdbc:oracle:thin:@1.234.5.158:11521/xe
# spring.datasource.username=ds200
# spring.datasource.password=pw200

# h2 또는 oracle 세션 사용
# server.servlet.session.timeout=3600
# spring.session.store-type=jdbc    
# spring.session.jdbc.initialize-schema=always

# db컨넥션 유지
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
spring.datasource.hikari.connection-timeout=600000
spring.datasource.hikari.maximum-pool-size=500
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.minimum-idle=20
spring.datasource.hikari.validation-timeout=3000
spring.datasource.hikari.idle-timeout=60000

# redis 세션 사용
spring.redis.host=1.234.5.158
spring.redis.port=16379
spring.redis.password=ds606
# 몽고DB에 사용했던 번호 ex) 201 -> 1
spring.redis.database=1
server.servlet.session.timeout=3600
spring.session.store-type=redis
spring.session.redis.flush-mode=immediate

2-2. global.properties

  • 환경설정 변수가 아님. 사용자 정의 변수
  • ex) 페이지 개수, default이미지 위치 등..
  • 여기에 정의하고 땡겨 써라
# 환경설정 변수가 아님. 사용자 정의 변수
# ex) 페이지 개수, default이미지 위치 등..
# 여기에 정의하고 땡겨 써라

# 페이지당 게시글 개수
board.page.count=10
# default 이미지 위치
default.image=classpath:/static/img/default.jpg

2-3. SecurityConfig

  • 접근권한
  • 로그인
  • 로그아웃
  • h2-console 접근권한
package com.example.config;

import com.example.service.UserDetailsServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 1. 직접 만든 DetailServiceImpl 객체 생성
    @Autowired
    UserDetailsServiceImpl mService;

    // 2. 회원가입시 했던 암호화 방법 객체생성, @Bean은 서버구동시 자동으로 객체생성
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 3. 직접만든 DetailServiceImpl에 암호화방법 적용
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(mService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super.configure(http);

        // 각 주소마다의(페이지 별) 접근 권한 부여
        http.authorizeRequests()
                .antMatchers("/admin", "/admin/**")
                .hasAnyAuthority("ADMIN")
                .antMatchers("/seller", "/seller/**")
                .hasAnyAuthority("ADMIN", "SELLER")
                .antMatchers("/customer", "/customer/**")
                .hasAnyAuthority("CUSTOMER")
                .anyRequest().permitAll(); // 나머지요청은 모두 허용
        
        // 로그인
        http.formLogin()
                .loginPage("/member/login")
                .loginProcessingUrl("/member/loginaction") // th:action 명
                .usernameParameter("uemail") // 아이디
                .passwordParameter("upw") // 패스워드
                // .successHandler(new MyLoginSuccessHandler()) // 성공했을때 명령을 수행
                .defaultSuccessUrl("/home", true) // 성공했을때 가는 페이지
                .permitAll();

        // 로그아웃
        http.logout()
                .logoutUrl("/member/logout") // 로그아웃 명령을 받을 주소
                // .logoutSuccessHandler(new MyLogoutSuccessHandler()) // 성공했을때 명령을 수행
                .logoutSuccessUrl("/home") // 로그아웃했을때 이동하는 페이지
                .invalidateHttpSession(true) // 세션 초기화
                .clearAuthentication(true) // 권한초기화
                .permitAll();

        // 접근권한 불가 페이지
        http.exceptionHandling().accessDeniedPage("/page403");

        // h2-console 사용하기 위해서
        http.csrf().ignoringAntMatchers("/h2-console/**");
        http.headers().frameOptions().sameOrigin();
    }

}
profile
The best

0개의 댓글