- Directory 구조
1. DB 모델링, 테이블 생성, 데이터 추가
member.sql
drop table if exists member_role;
drop table if exists member;
CREATE TABLE `member` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'member id',
`name` VARCHAR(255) NOT NULL COMMENT 'member name',
`password` VARCHAR(255) NOT NULL COMMENT '암호회된 password',
`email` VARCHAR(255) NOT NULL UNIQUE COMMENT 'login id, email',
`create_date` DATETIME NULL DEFAULT NULL COMMENT '등록일',
`modify_date` DATETIME NULL DEFAULT NULL COMMENT '수정일',
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `member_role` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'role id',
`member_id` INT(11) NOT NULL COMMENT 'member id fk',
`role_name` VARCHAR(100) NOT NULL COMMENT 'role 이름 ROLE_ 로 시작하는 값이어야 한다.',
PRIMARY KEY (`id`),
FOREIGN KEY (`member_id`)
REFERENCES `member` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into member (id, name, password, email, create_date, modify_date) values ( 1, '최호연', '$2a$10$xgWp2kXNabPQys6CBRShwOmz7f4/u6Gxf38XJkcGe/HHJak7t.Akm', 'oyeon@example.com', now(), now());
insert into member (id, name, password, email, create_date, modify_date) values ( 2, '김원기', '$2a$10$xgWp2kXNabPQys6CBRShwOmz7f4/u6Gxf38XJkcGe/HHJak7t.Akm', 'nexon@example.com', now(), now());
insert into member_role (id, member_id, role_name) values (1, 1, 'ROLE_USER');
insert into member_role (id, member_id, role_name) values (2, 1, 'ROLE_ADMIN');
insert into member_role (id, member_id, role_name) values (3, 2, 'ROLE_USER');
EER Diagram
2. DB 의존성 추가
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.edwith.webbe</groupId>
<artifactId>securityexam</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>securityexam Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring.version>5.2.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.2-b02</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. DB 연동을 위한 설정 파일 수정
ApplicationConfig.java
package org.edwith.webbe.securityexam.config;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
@ComponentScan(basePackages = {"org.edwith.webbe.securityexam.dao", "org.edwith.webbe.securityexam.service"})
@EnableTransactionManagement
public class ApplicationConfig implements TransactionManagementConfigurer {
private String driverClassName = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/connectdb?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
private String username = "connectuser";
private String password = "connect123!@#";
@Bean
public DataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return transactionManager();
}
}
4. DB 데이터를 읽기위한 DTO, DAO
Member.java
- 회원 정보를 저장하는 Member DTO 클래스
package org.edwith.webbe.securityexam.dto;
import java.util.Date;
public class Member {
private Long id;
private String name;
private String password;
private String email;
private Date createDate;
private Date modifyDate;
public Member(){
createDate = new Date();
modifyDate = new Date();
}
public Member(Long id, String name, String password, String email){
this();
this.name = name;
this.password = password;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
@Override
public String toString() {
return "Member [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", createDate="
+ createDate + ", modifyDate=" + modifyDate + "]";
}
}
MemberDaoSqls.java
- email 정보와 일치하는 한 건의 회원 정보를 읽어들인다.
package org.edwith.webbe.securityexam.dao;
public class MemberDaoSqls {
public static final String SELECT_ALL_BY_EMAIL = "SELECT id, name, password, email, create_date, modify_date FROM member WHERE email = :email";
}
MemberDao.java
- 회원 정보를 읽어들이는 MemberDao 클래스
package org.edwith.webbe.securityexam.dao;
import org.edwith.webbe.securityexam.dto.Member;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Repository
public class MemberDao {
private NamedParameterJdbcTemplate jdbc;
private RowMapper<Member> rowMapper = BeanPropertyRowMapper.newInstance(Member.class);
public MemberDao(DataSource dataSource){
this.jdbc = new NamedParameterJdbcTemplate(dataSource);
}
public Member getMemberByEmail(String email){
Map<String, Object> map = new HashMap<>();
map.put("email", email);
return jdbc.queryForObject(MemberDaoSqls.SELECT_ALL_BY_EMAIL, map, rowMapper);
}
}
MemberRole.java
- 회원의 권한(Role)정보를 저장하기 위한 MemberRole DTO 클래스
package org.edwith.webbe.securityexam.dto;
public class MemberRole {
private Long id;
private Long memberId;
private String roleName;
public MemberRole(){
}
public MemberRole(Long memberId, String roleName){
this.memberId = memberId;
this.roleName = roleName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public String toString() {
return "MemberRole [id=" + id + ", memberId=" + memberId + ", roleName=" + roleName + "]";
}
}
MemberRoleDaoSqls.java
- email에 해당하는 권한 정보를 읽어들이기 위해서 member테이블과 member_role테이블을 조인(JOIN)하여 결과를 얻는다.
package org.edwith.webbe.securityexam.dao;
public class MemberRoleDaoSqls {
public static final String SELECT_ALL_BY_EMAIL = "SELECT mr.id, mr.member_id, mr.role_name FROM member_role mr JOIN member m ON mr.member_id = m.id WHERE m.email = :email";
}
MemberRoleDao.java
- 권한 정보를 읽어들이는 MemberRoleDao 클래스
package org.edwith.webbe.securityexam.dao;
import org.edwith.webbe.securityexam.dto.MemberRole;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class MemberRoleDao {
private NamedParameterJdbcTemplate jdbc;
private RowMapper<MemberRole> rowMapper = BeanPropertyRowMapper.newInstance(MemberRole.class);
public MemberRoleDao(DataSource dataSource){
this.jdbc = new NamedParameterJdbcTemplate(dataSource);
}
public List<MemberRole> getRolesByEmail(String email){
Map<String, Object> map = new HashMap<>();
map.put("email", email);
return jdbc.query(MemberRoleDaoSqls.SELECT_ALL_BY_EMAIL, map, rowMapper);
}
}
MemberDaoTest.java
- DB 접속, MemberDao, MemberRoleDao 클래스가 알맞게 동작하는지 테스트 클래스를 작성
package org.edwith.webbe.securityexam.dao;
import org.edwith.webbe.securityexam.config.ApplicationConfig;
import org.edwith.webbe.securityexam.dto.Member;
import org.edwith.webbe.securityexam.service.security.UserEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.Connection;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class})
public class MemberDaoTest {
@Autowired
DataSource dataSource;
@Autowired
MemberDao memberDao;
@Autowired
MemberRoleDao memberRoleDao;
@Test
public void configTest() throws Exception{
}
@Test
public void connnectionTest() throws Exception{
Connection connection = dataSource.getConnection();
Assert.assertNotNull(connection);
}
@Test
public void getUser() throws Exception{
Member member = memberDao.getMemberByEmail("oyeon@example.com");
Assert.assertNotNull(member);
Assert.assertEquals("최호연", member.getName());
}
}
MemberServiceImpl.java
package org.edwith.webbe.securityexam.service;
import org.edwith.webbe.securityexam.dao.MemberDao;
import org.edwith.webbe.securityexam.dao.MemberRoleDao;
import org.edwith.webbe.securityexam.dto.Member;
import org.edwith.webbe.securityexam.dto.MemberRole;
import org.edwith.webbe.securityexam.service.security.UserEntity;
import org.edwith.webbe.securityexam.service.security.UserRoleEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
public class MemberServiceImpl implements MemberService {
private final MemberDao memberDao;
private final MemberRoleDao memberRoleDao;
public MemberServiceImpl(MemberDao memberDao, MemberRoleDao memberRoleDao) {
this.memberDao = memberDao;
this.memberRoleDao = memberRoleDao;
}
@Override
@Transactional
public UserEntity getUser(String loginUserId) {
Member member = memberDao.getMemberByEmail(loginUserId);
return new UserEntity(member.getEmail(), member.getPassword());
}
@Override
@Transactional
public List<UserRoleEntity> getUserRoles(String loginUserId) {
List<MemberRole> memberRoles = memberRoleDao.getRolesByEmail(loginUserId);
List<UserRoleEntity> list = new ArrayList<>();
for(MemberRole memberRole : memberRoles) {
list.add(new UserRoleEntity(loginUserId, memberRole.getRoleName()));
}
return list;
}
}
결과
- 권한이 있는 데이터에 대해서만 로그인 허용