티스토리 뷰

Spring

Spring Security (Spring Boot) #4

§무명소졸§ 2020. 2. 28. 11:47

지난번 처럼 메모리를 이용한 사용자 정보 저장은 Demo 등 인트라넷 내에서 운영하는 간단한 시스템일 경우 사용하고 대부분에 경우 사용하지 않는다. 오늘은 DB를 이용해 사용자를 로그인 처리하겠다.

H2 database

스프링부트에 embded되어 있는 H2 database 를 사용하겠다.  이런 간단한 예제 애플리케이션을 만들거나 할때 사용하기 간편하다.

pom.xml

pom.xml 파일에 dependency 를 추가한다. 

<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<version>1.3.148</version>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

S1SecurityConfiguration

두 라인은 h2 Db사용에 있어서 필수적인 부분이다. 

http.csrf().disable();
http.headers().frameOptions().sameOrigin(); 

application.yml

h2 database의 연결 정보및 datasource 정보를 등록한다.

spring:
  h2:
    console:
      enabled: true
      path: /h2
  datasource:
    url: jdbc:h2:file:~/s1db
    username: sa
    password:
    driverClassName: org.h2.Driver

H2 Console

설정이 완료되면 Spring Boot를 기동하고 http://localhost:8080/h2 접속하면 아래와 같은 H2 Console 화면에 접속할 수 있다. DB를 사용할수 있게 준비가 된 것이다.

 

테이블 생성 및 데이터 초기화

사용자 정보와 권한테이블을 생성하고 유저 데이터를 1건 저장한다. 릴레이션은 생략하고 최대한 간략히 생성했다. 패스워드는 BCryptPasswordEncoder 로 hexing된 문자열을 입력한다.

    public static void main(String[] args) {
        BCryptPasswordEncoder b = new BCryptPasswordEncoder();
        System.out.println(b.encode("1234"));
    }
CREATE  TABLE users (
  userid VARCHAR(45) NOT NULL ,
  userpassword VARCHAR(255) NOT NULL ,
  useyn boolean);




CREATE  TABLE users_role (
  userid VARCHAR(45) NOT NULL ,
  userrole VARCHAR(45) NOT NULL);


Insert into users values('m2sj', '$2a$10$3M68wfZrRxXCHf5UzeMmSOK8o/6A9rxb9F6kWfcrZN9SbdiVKVsy.', true);

Insert into users_role values('m2sj', 'ADMIN');

 

Java Configuration

이제 스프링 Security에서 DB연결을 통한 로그인 처리를위해 java 파일들을 추가하겠다.

DbConfig

datasource 스프링 Bean을 생성하기위한 java configuration 클래스이다.

@Configuration
public class DbConfig {
    @Bean
    public DataSource getDataSource() {
        return DataSourceBuilder.create().username("sa").url("jdbc:h2:file:~/s1db").build();
    }
}

 

S1SecurityConfiguration 

패스워드 인코딩을위한 Bean설정과 로그인 인증처리 클래스를 변경한다.

   @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder br = new BCryptPasswordEncoder();
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       /* auth.inMemoryAuthentication()
                .withUser("m2sj").password("{noop}1234").authorities("USER")
                .and()
                .withUser("admin").password("{noop}1234").authorities("ADMIN");*/
       auth.jdbcAuthentication().dataSource(dataSource)
               .passwordEncoder(passwordEncoder())
               .usersByUsernameQuery("select userid, userpassword, useyn from users where userid = ?")
               .authoritiesByUsernameQuery("select userid, userrole from users_role where userid = ?");
    }

 

테스트

이제 스프링 부트를 재기동하고 localhost:8080/login 페이지로 이동한다. m2sj / 1234 를 입력하면 정상 처리된 것을 확인할 수 있다.

 

전체 소스는 주소에서 Clone 후 #4 tag로 checkout 후 확인이 가능하다.
https://github.com/warpgate3/sss.git

git clone https://github.com/warpgate3/sss.git
git checkout tags/#4

 

'Spring' 카테고리의 다른 글

H2 Console in WebFlux  (0) 2020.07.28
static resources in spring boot  (0) 2020.07.11
Spring boot 2.x + ehcache 3.x  (1) 2020.01.30
Spring Security (Spring Boot) #3 form login customize  (0) 2020.01.20
Spring Security (Spring Boot) #2  (0) 2020.01.10
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크