최초반영

This commit is contained in:
nhj 2025-08-11 17:51:56 +09:00
commit d2d4c5d4a2
85 changed files with 3795 additions and 0 deletions

23
.classpath Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-16/"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer">
<attributes>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin/default"/>
</classpath>

6
.gitattributes vendored Normal file
View File

@ -0,0 +1,6 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

41
.project Normal file
View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>urpItms_00_Auth</name>
<comment>Project lib created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,13 @@
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=
jvm.arguments=
offline.mode=false
override.workspace.settings=false
show.console.view=false
show.executions.view=false

View File

@ -0,0 +1,4 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=16
org.eclipse.jdt.core.compiler.compliance=16
org.eclipse.jdt.core.compiler.source=16

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="urpItms_00_Auth">
<property name="context-root" value="urpItms_00_Auth"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="src/main/java"/>
<wb-resource deploy-path="/" source-path="src/main/webapp"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jst.java" version="16"/>
</faceted-project>

View File

@ -0,0 +1,2 @@
boot.validation.initialized=true
eclipse.preferences.version=1

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://109.26.11.21:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.10.10.203:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 12000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.10.10.203:3306/ur_itms_rel_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: YvRZ5jyhmB6gwVSUGBOqNMQB00k6OZZSfUH5ZU4GEFs=
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,38 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
# jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.138:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/main/jwtkey.jks Normal file

Binary file not shown.

View File

@ -0,0 +1,2 @@
log4jdbc.spylogdelegator.name = net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
log4jdbc.dump.sql.maxlinelength=0

100
bin/main/logback-spring.xml Normal file
View File

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<contextName>${HOSTNAME}</contextName>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
</appender>
<!--
<root level="error">
<appender-ref ref="consoleAppender" />
</root>
<logger name="TRACE_LOGGER" level="error" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
-->
<root level="info">
<appender-ref ref="consoleAppender" />
</root>
<logger name="TRACE_LOGGER" level="info" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
<!-- 일단 사용하지 않음 -->
<!--
<property name="LOG_DIR" value="/var/log/LAMP" />
<springProfile name="!local">
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>
<file>${LOG_DIR}/${HOSTNAME}_server.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${HOSTNAME}_server.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>10</maxHistory>
</rollingPolicy>
</appender>
<appender name="asyncAppender" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>10000</queueSize>
<appender-ref ref="rollingFileAppender" />
</appender>
<appender name="traceRollingFileAppend" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%msg%n</Pattern>
</encoder>
<file>${LOG_DIR}/${HOSTNAME}_trace.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${HOSTNAME}_trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>10</maxHistory>
</rollingPolicy>
</appender>
<appender name="traceLogAppend" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>10000</queueSize>
<appender-ref ref="traceRollingFileAppend" />
</appender>
<root level="info">
<appender-ref ref="asyncAppender" />
</root>
<logger name="TRACE_LOGGER" level="info" additivity="false">
<appender-ref ref="traceLogAppend" />
</logger>
</springProfile>
-->
</Configuration>

View File

@ -0,0 +1,4 @@
ows.log.path=C://ode/logs/was
ows.log.level=debug
ows.log.filename=ows_adm_log
ows.log.err.filename=ows_adm_log_error

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="defaultStatementTimeout" value="1800"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="defaultFetchSize" value="1000" />
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
-->
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="defaultStatementTimeout" value="1800"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="defaultFetchSize" value="1000" />
<setting name="mapUnderscoreToCamelCase" value="false"/>
</settings>
<typeAliases>
<typeAlias alias="MemberVO" type="com.urpsys.baseauth.domain.MemberVO" />
</typeAliases>
<!--
<typeAliases>
<typeAlias alias="UserVO" type="com.gdsc.ImgEd.domain.UserVO" />
<typeAlias alias="ImageInfoVO" type="com.gdsc.ImgEd.domain.ImageInfoVO" />
<typeAlias alias="ImageMetaVO" type="com.gdsc.ImgEd.domain.ImageMetaVO" />
<typeAlias alias="IspnMngInfoVO" type="com.gdsc.ImgEd.domain.IspnMngInfoVO" />
<typeAlias alias="IspnMngInfo2VO" type="com.gdsc.ImgEd.domain.IspnMngInfo2VO" />
<typeAlias alias="IspnMngInfo4VO" type="com.gdsc.ImgEd.domain.IspnMngInfo4VO" />
<typeAlias alias="IspnMngInfo5VO" type="com.gdsc.ImgEd.domain.IspnMngInfo5VO" />
</typeAliases>
-->
</configuration>

View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.urpsys.baseauth.dao.MemberDao">
<select id="actionLogin" parameterType="string" resultType="MemberVO">
<![CDATA[
SELECT A.USER_ID AS strMEM_ID
, A.USER_NM AS strMEM_NM
, '' AS strRRNO
, A.PASSWORD AS strPWD
, A.USER_EMAIL AS strMEM_EML_ADDR
, A.USER_SE AS userSe
, A.ORGNZT_ID AS orgnztId
, A.GROUP_ID AS strGRP_ID
, A.ESNTL_ID AS strESNTL_ID
, A.ESNTL_ID AS uniqId
, B.AUTH_CD AS strAuthCd
FROM COMVNUSERMASTER A
, TB_USER_CRYP_CNF B
WHERE A.USER_ID = #{loginId}
AND A.ESNTL_ID = B.CRYP_CNF_TRG_ID
]]>
</select>
<select id="getLastConnectTime" parameterType="string" resultType="string">
<![CDATA[
SELECT DATE_FORMAT ( IFNULL(MAX(CRT_DTM), NOW()), '%Y-%m-%d %H:%i:%s')
FROM TB_ACES_LOG
WHERE ACES_ID = #{uniqId}
]]>
</select>
<!-- 로그인인증제한 조회 -->
<select id="selectLoginIncorrect" parameterType="string" resultType="java.util.LinkedHashMap">
SELECT TASK_USER_ID AS userId
, PWD AS userPw
, USER_NM AS userNm
, ESNTL_ID AS uniqId
, IFNULL(LOCK_AT,'N') AS lockAt
, IFNULL(LOCK_NCNT,0) AS lockNcnt
FROM TB_TASK_USER_INFO
WHERE TASK_USER_ID = #{id}
</select>
<update id="updateLoginLockAdd" parameterType="string" >
UPDATE TB_TASK_USER_INFO
SET LOCK_AT = CASE WHEN LOCK_NCNT > 1 THEN 'Y'
ELSE ''
END
, LOCK_NCNT = IFNULL(LOCK_NCNT,0)+1
, LAST_CHG_DTM = sysdate()
WHERE TASK_USER_ID = #{id}
</update>
<update id="updateLoginLockCancel" parameterType="string" >
UPDATE TB_TASK_USER_INFO
SET LOCK_AT = NULL
, LOCK_NCNT = NULL
, LAST_CHG_DTM = sysdate()
WHERE TASK_USER_ID = #{id}
</update>
</mapper>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gdsc.ImgEd.dao.UserDao">
<select id="imageMetaBackup" parameterType="string" resultType="string">
<![CDATA[
select '1'
]]>
</select>
</mapper>

View File

@ -0,0 +1 @@
aes256.key=52f48aa1c7435bc11bf909d9d7d1d5932f4bacd8184ec5c1eed6d03ee17fe126

Binary file not shown.

93
build.gradle Normal file
View File

@ -0,0 +1,93 @@
plugins
{
id 'org.springframework.boot' version '2.6.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
id 'java'
id 'war'
}
group = 'com.urpsys'
version = '1.0.0-SNAPSHOT'
sourceCompatibility = '16'
configurations
{
compileOnly
{
extendsFrom annotationProcessor
}
}
repositories
{
mavenCentral()
}
ext
{
set('snippetsDir', file("build/generated-snippets"))
}
dependencies
{
implementation 'org.springframework.boot:spring-boot-starter-batch'
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-integration'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-quartz'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation ('org.springframework.boot:spring-boot-starter-web')
{
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' // DB
// compileOnly 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2' // DB
// mariadb connect lib
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' // mariadb
// oracle connect lib
// implementation group: 'com.oracle.database.jdbc', name: 'ojdbc8', version: '21.8.0.0'
// http
implementation 'org.springframework.boot:spring-boot-starter-undertow'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
// log
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'commons-codec:commons-codec:1.15' //
implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16' // sql log
implementation 'org.apache.commons:commons-lang3:3.12.0'
implementation 'org.springframework.boot:spring-boot-starter-security' //
implementation 'org.springframework.security:spring-security-jwt:1.0.9.RELEASE' //
implementation group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.3.4.RELEASE' // spring oauth 2.0
implementation group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.3.3'
}
test
{
outputs.dir snippetsDir
useJUnitPlatform()
}
asciidoctor
{
inputs.dir snippetsDir
dependsOn test
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

11
settings.gradle Normal file
View File

@ -0,0 +1,11 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user manual at https://docs.gradle.org/7.4.2/userguide/multi_project_builds.html
*/
rootProject.name = 'urpItms_00_Auth'

View File

@ -0,0 +1,142 @@
package com.urpsys.baseauth;
import java.io.InputStream;
import java.security.InvalidKeyException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
* Hello world!
*
*/
public class Aes256UrpPortalAuth
{
private static SecretKey keySpec; // keySpec
private static IvParameterSpec ivSpec; // ivSpec
public static void main( String[] args )
{
InputStream fis = null;
String secretKey = null;
System.out.println( "Hello World!" );
secretKey = "52f48aa1c7435bc11bf909d9d7d1d5932f4bacd8184ec5c1eed6d03ee17fe126";
String strChgMethod = "";
String strChgInput = "";
if(args.length !=2 )
{
System.out.println("Invalid args , args length 2 input ");
strChgMethod = "enc";
strChgInput = "123456";
// System.exit(0);
}
else
{
strChgMethod = args[0];
strChgInput = args[1];
}
try
{
byte[] secretKeyBytes = Hex.decodeHex(secretKey);
if (secretKeyBytes.length != 32)
{
System.out.println("Invalid key (key length is not valid) ");
System.exit(0);
}
byte[] ivBytes = new byte[16];
System.arraycopy(secretKeyBytes, 0, ivBytes, 0, 16);
keySpec = new SecretKeySpec(secretKeyBytes, "AES");
ivSpec = new IvParameterSpec(ivBytes);
if(strChgMethod.equals("enc"))
{
System.out.println( "암호로 변경" );
if (strChgInput == null)
{
System.out.println("변경할 문자열이 없습니다.");
}
String encryptedStr = null;
try
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(strChgInput.getBytes("UTF-8"));
encryptedStr = new String(Base64.encodeBase64(encrypted));
}
catch (Exception ex)
{
ex.printStackTrace();
}
System.out.println( "["+ strChgInput +"] 암호화로 변경 =============>"+ encryptedStr);
}
else if(strChgMethod.equals("dec"))
{
System.out.println( "평문으로 변경" );
if (strChgInput == null)
{
System.out.println("변경할 문자열이 없습니다.");
}
String decryptedStr = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
if(strChgInput != null)
{
byte[] bChgInput = strChgInput.getBytes("UTF-8");
byte[] byteStr = null;
if(bChgInput != null)
{
byteStr = Base64.decodeBase64(bChgInput);
}
decryptedStr = new String(cipher.doFinal(byteStr), "UTF-8");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
System.out.println( "["+ strChgInput +"] 평문으로 변경 =============>"+ decryptedStr);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,456 @@
package com.urpsys.baseauth.common;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.Vector;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.urpsys.baseauth.common.exception.CustomException;
/**
* 공통 유틸리티를 모아둔 클래스
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
public class CommonUtil
{
/**
* nvl 메소드
* @param inputStr
* @return
*/
public static String nvl(String inputStr) {
return (inputStr != null) ? inputStr.trim() : "";
}
/**
* nvl 메소드
* @param inputStr
* @param defaultValue
* @return
*/
public static String nvl(String inputStr, String defaultValue) {
return nvl(inputStr).contentEquals("") ? defaultValue : inputStr.trim();
}
/**
* nvl 메소드
* @param inputObj
* @return
*/
public static String nvl(Object inputObj) {
return (inputObj != null) ? String.valueOf(inputObj).trim() : "";
}
/**
* long 타입의 시간을 입력받아 날짜 형태로 변환해서 리턴해주는 함수
*
* @param longTime long type 시간
* @param dateFormat 변환할 포맷
* @return 변환된 날짜 String
* @throws SystemException
*/
public static String getTimeString(long longTime, String dateFormat) throws CustomException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.KOREA);
if (longTime < 0)
{
return "";
}
else {
try {
return sdf.format(new Date(longTime));
} catch (Exception e) {
throw new CustomException("Date 변환 오류");
}
}
}
/**
* 현재(한국기준) 시간정보를 얻는다.<BR>
* () 입력파리미터인 format string에 "yyyyMMddhh" 셋팅하면 1998121011과 같이 Return.<BR>
* () format string에 "yyyyMMddHHmmss" 셋팅하면 19990114232121과 같이
* 0~23시간 타입으로 Return. <BR>
* String CurrentDate = CtosUtil2.getKST("yyyyMMddHH");<BR>
* @param format 얻고자하는 현재시간의 Type
* @return str 현재 한국 시간.
*/
public static String getKST(String format)
{
//1hour(ms) = 60s * 60m * 1000ms
int millisPerHour = 60 * 60 * 1000;
SimpleDateFormat fmt= new SimpleDateFormat(format);
SimpleTimeZone timeZone = new SimpleTimeZone(9*millisPerHour,"KST");
fmt.setTimeZone(timeZone);
long time=System.currentTimeMillis();
String str=fmt.format(new java.util.Date(time));
return str;
}
/**
* 입력한 날짜 기준으로 몇일 , (주의)입력날짜는 구분자가 없는 string형
*
* @param date
* string date (19991002)
* @param Day
* 기준이 되는 시간
* @return String
*/
public static String getDatewithSpan(String date, long Day)
{
/*
* int millisPerHour = 60 * 60 * 1000; SimpleDateFormat fmt= new
* SimpleDateFormat("yyyy/MM/dd"); SimpleTimeZone timeZone = new
* SimpleTimeZone(9*millisPerHour,"KST"); fmt.setTimeZone(timeZone);
*
* int year = Integer.valueOf(date.substring(0,4)).intValue(); int month
* = Integer.valueOf(date.substring(4,6)).intValue(); int day =
* Integer.valueOf(date.substring(6,8)).intValue();
*
* java.util.Calendar aDay = Calendar.getInstance();
* aDay.set(year+1900,month,day); java.util.Calendar bDay
* =Calendar.getInstance(); bDay.set(1970+1900,1,1); java.util.Date cDay
* = new java.util.Date((aDay.getTime()).getTime() -
* (bDay.getTime()).getTime() + ((Day+1)*86400000) );
*
* return fmt.format(cDay);
*/
// 2006-09-04 7:03오후 오동원수정
String vFORMAT = "yyyy/MM/dd";
return getDatewithSpan(date, Day, "D", vFORMAT);
}
/**
* 입력한 날짜 기준으로 (,시간,) , (주의)입력날짜는 구분자가 없는 string형<br>
*
* @param date
* string date (20000315/2000031509/200003150915)
* @param unit
* long unit: (,시간,) , (,시간,)
* @param type
* String type: D:Day H:Hour M:Minute
* @return String 계산된 문자열의 .
*/
public static String getDatewithSpan(String date, long unit, String type, String strFormatType)
{
/*
* String formatType = strFormatType; int ihour = 0; int itime = 0;
*
* long dhm = 24 * 60 * 60 * 1000;
*
* if (type.equals("D")) { dhm =dhm + unit * 24 * 60 * 60 * 1000; } else
* if (type.equals("H")){ dhm =dhm + unit * 60 * 60 * 1000; } else if
* (type.equals("M")){ dhm =dhm + unit * 60 * 1000; } else{ return type
* + "은 부적절한 Type값입니다"; }
*
* switch (date.length()){ case (8): if (type.equals("H") ||
* type.equals("M")) { return "HM-ERROR"; }
*
* break; case (10): if (type.equals("M")) { return "M-ERROR"; }
*
* ihour = Integer.valueOf(date.substring(8,10)).intValue(); break; case
* (12):
*
* ihour = Integer.valueOf(date.substring(8,10)).intValue(); itime =
* Integer.valueOf(date.substring(10,12)).intValue(); break; default:
* return "date Length Error"; }
*
* int millisPerHour = 60 * 60 * 1000; SimpleDateFormat fmt= new
* SimpleDateFormat(formatType); SimpleTimeZone timeZone = new
* SimpleTimeZone(9*millisPerHour,"KST"); fmt.setTimeZone(timeZone);
*
* int iyear = Integer.valueOf(date.substring(0,4)).intValue(); int
* imonth = Integer.valueOf(date.substring(4,6)).intValue(); int iday =
* Integer.valueOf(date.substring(6,8)).intValue(); java.util.Calendar
* aDay = Calendar.getInstance();
* aDay.set(iyear+1900,imonth,iday,ihour,itime); java.util.Calendar bDay
* = Calendar.getInstance(); bDay.set(1970+1900,1,1,9,0); java.util.Date
* cDay = new java.util.Date((aDay.getTime()).getTime() -
* (bDay.getTime()).getTime() + dhm); return fmt.format(cDay);
*/
// 2006-09-04 7:03오후 오동원수정
String formatType = strFormatType;
int ihour = 0;
int itime = 0;
if(!(type.equals("D") || type.equals("H") || type.equals("M")))
{
return type + "은 부적절한 Type값입니다";
}
switch(date.length())
{
case (8):
if(type.equals("H") || type.equals("M"))
{
return "HM-ERROR";
}
break;
case (10):
if(type.equals("M"))
{
return "M-ERROR";
}
ihour = Integer.parseInt(date.substring(8, 10));
// ihour = Integer.valueOf(date.substring(8, 10)).intValue();
break;
case (12):
ihour = Integer.parseInt(date.substring(8, 10));
itime = Integer.parseInt(date.substring(10, 12));
// ihour = Integer.valueOf(date.substring(8, 10)).intValue();
// itime = Integer.valueOf(date.substring(10, 12)).intValue();
break;
default:
return "date Length Error";
}
int iyear = Integer.parseInt(date.substring(0, 4));
int imonth = Integer.parseInt(date.substring(4, 6));
int iday = Integer.parseInt(date.substring(6, 8));
/*
int iyear = Integer.valueOf(date.substring(0, 4)).intValue();
int imonth = Integer.valueOf(date.substring(4, 6)).intValue();
int iday = Integer.valueOf(date.substring(6, 8)).intValue();
*/
int imonth1 = imonth - 1; // 달은 0달부터 시작한다.
java.util.Calendar zDay = Calendar.getInstance();
zDay.set(iyear, imonth1, iday, ihour, itime);
if(type.equals("D"))
{
zDay.add(Calendar.DATE, (int) unit);
}
else if(type.equals("H"))
{
zDay.add(Calendar.HOUR_OF_DAY, (int) unit);
}
else if(type.equals("M"))
{
zDay.add(Calendar.MINUTE, (int) unit);
}
else
{
return type + "은 부적절한 Type값입니다";
}
java.util.Date z1Day = zDay.getTime();
java.text.SimpleDateFormat fmt2 = new java.text.SimpleDateFormat(formatType);
return fmt2.format(z1Day);
}
/**
* 현재 시간을 기준으로 일후 시간 시간의 형태는 (yyyy/mm/dd)
*
* @param day
* 더하려는 날짜
* @return str 현재 시간에 입력 시간을 더한 DATE형 시간
*/
public static String getDatewithSpan(long day)
{
/*
* int millisPerHour = 60 * 60 * 1000; SimpleDateFormat fmt= new
* SimpleDateFormat("yyyy/MM/dd"); SimpleTimeZone timeZone = new
* SimpleTimeZone(9*millisPerHour,"KST"); fmt.setTimeZone(timeZone);
*
* long time = System.currentTimeMillis(); long span = ( 60 * 60 * 1000
* * 24 ) * day; //하루에 대한 millisecond... long time2 = time + span;
* String str=fmt.format(new java.util.Date(time2));
*
* return str;
*/
String strSYSDATE = CommonUtil.getKST("yyyyMMddHH"); // 지금 시간
String vFORMAT = "yyyy/MM/dd";
return getDatewithSpan(strSYSDATE, day, "D", vFORMAT);
}
public static long stol(String str)
{
if(str == null ) return 0;
return (Long.valueOf(str).longValue());
}
/**
문자열을 특정 문자열을 변환시킨다.
@version 1.0
@author Yoon Su-wan
@since JDK1.0
@param targeter 대상문자열
@param target_str 변환될 대상문자열
@param replace_str 변환될 문자열
@return target_str이 replace_str로 변환된 문자열
*/
public static String getReplacedString(String targeter, String target_str, String replace_str)
{
if( targeter == null
|| target_str == null
|| replace_str == null )
return "debug : parameter value is null";
if(target_str.length() == 0)
return targeter;
StringBuffer str = new StringBuffer();
int start_ptr = 0;
int current_ptr = 0;
int increment_size = replace_str.length();
if(increment_size == 0 ) increment_size = 1;
while((current_ptr = targeter.indexOf(target_str, start_ptr)) != -1)
{
str.append(targeter.substring(start_ptr, current_ptr));
str.append(replace_str);
start_ptr = current_ptr + increment_size;
if(start_ptr >= targeter.length())
break;
}//end while
if(start_ptr == 0)
return targeter;
if(start_ptr < targeter.length())
str.append(targeter.substring(start_ptr));
return str.toString();
}//getReplacedString(String targeter, String target_str, String replace_str)
/**
받은메세지에서 v_s1값을 찾아서 v_s2로 대치한다.
@version 1.0
@author Yoon Su-wan
@since JDK1.0
@param v_msg 대상문자열
@param v_s1 변환될 대상문자열
@param v_s2 변환될 문자열
@return v_s1이 v_s2 변환된 문자열
*/
public static String getReplacedString2(String v_msg, String v_s1, String v_s2)
{
int idx = v_msg.indexOf(v_s1);
if (idx == -1) return v_msg;
else
{
try
{
return v_msg.substring(0, idx) + v_s2 + v_msg.substring(idx+2);
} catch (Exception e)
{
return v_msg.substring(0, idx) + v_s2;
}
}
}
public static String getReplacedString3(String sStr, String n1, String n2)
{
int iTmp = 0;
if (sStr == null) return "";
String sTmp = sStr;
StringBuffer sbSave = new StringBuffer();
sbSave.append("");
while (sTmp.indexOf(n1) > -1)
{
iTmp = sTmp.indexOf(n1);
sbSave.append(sTmp.substring(0,iTmp));
sbSave.append(n2);
sTmp = sTmp.substring(iTmp + n1.length());
}
sbSave.append(sTmp);
return sbSave.toString();
}
public static Vector arrToDouVector(String strArray, String strDelimt)
{
String[] stArray = strArray.split(strDelimt);
double[] dArray = Arrays.stream(stArray).mapToDouble(Double::parseDouble).toArray();
Vector vReturn = new Vector();
if(dArray==null) return vReturn;
for(double dTemp: dArray)
{
vReturn.add(dTemp);
}
return vReturn;
}
public static String arrListToString(List list)
{
String strReturn="";
if(list == null ) return "";
for(int i=0; i<list.size(); i++)
{
String strTemp = list.get(i)+"";
// System.out.println("한번 봅시다=>"+strTemp);
// double dou = Double.parseDouble(strTemp);
// strReturn = strReturn+","+dou;
strReturn = strReturn+","+strTemp;
}
strReturn = strReturn.substring(1);
return strReturn;
}
/**
Map 데이터를 JSONObject로 변환.
@version 1.0
@author Yoon Su-wan
@since JDK1.0
@param v_msg Map
@return JSONObject
*/
public static JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException
{
JSONObject jsonData = new JSONObject();
for (String key : map.keySet())
{
Object value = map.get(key);
if (value instanceof Map<?, ?>)
{
value = getJsonFromMap((Map<String, Object>) value);
}
jsonData.put(key, value);
}
return jsonData;
}
}

View File

@ -0,0 +1,111 @@
package com.urpsys.baseauth.common;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.urpsys.baseauth.common.crypto.Aes256Cipher;
import com.urpsys.baseauth.common.exception.CustomException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
/**
* Datasource 생성하는 유틸리티
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
public class DataSourceUtil
{
/**
* 데이터 소스 만드는 메소드
* @param dataSourceName
* @param env
* @param cipher
* @return
*/
public static DataSource createDataSource(String dataSourceName, Environment env, Aes256Cipher cipher)
{
HikariConfig config = new HikariConfig();
config.setDriverClassName (env.getProperty(dataSourceName + ".driverClassName" ));
config.setJdbcUrl (env.getProperty(dataSourceName + ".jdbcUrl" ));
config.setUsername (cipher.decrypt(env.getProperty(dataSourceName + ".username")));
config.setPassword (cipher.decrypt(env.getProperty(dataSourceName + ".password")));
config.setAutoCommit(false);
config.setMaximumPoolSize (Integer.parseInt(env.getProperty(dataSourceName + ".maximumPoolSize" )));
config.setMinimumIdle (Integer.parseInt(env.getProperty(dataSourceName + ".minimumIdle" )));
config.setConnectionTimeout (Long.parseLong (env.getProperty(dataSourceName + ".connectionTimeout" )));
config.setIdleTimeout (Long.parseLong (env.getProperty(dataSourceName + ".idleTimeout" )));
config.addDataSourceProperty("cachePrepStmts" , "true");
config.addDataSourceProperty("prepStmtCacheSize" , "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit" , "2048");
return new HikariDataSource(config);
}
/**
* SqlSessionFactory 만드는 메소드
* @param dataSource
* @param configLocation
* @param mapperLocation
* @return
* @throws CustomException
*/
public static SqlSessionFactory createSqlSessionFactory(DataSource dataSource, Resource configLocation,
Resource[] mapperLocation) throws CustomException
{
SqlSessionFactory sqlSessionFactory;
try {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setConfigLocation(configLocation);
sessionFactoryBean.setMapperLocations(mapperLocation);
sqlSessionFactory = sessionFactoryBean.getObject();
}
catch (Exception ex)
{
throw new CustomException(ex.getMessage());
}
return sqlSessionFactory;
}
/**
* 트랜잭션 처리 메소드
* @param dataSource
* @return
*/
public static DataSourceTransactionManager createTxManager(DataSource dataSource)
{
DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);
txManager.setGlobalRollbackOnParticipationFailure(false);
return txManager;
}
//end method
}

View File

@ -0,0 +1,142 @@
package com.urpsys.baseauth.common.crypto;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.springframework.core.io.ClassPathResource;
import com.urpsys.baseauth.common.CommonUtil;
/**
* aes 256 암호화 클래스
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
public class Aes256Cipher
{
private SecretKey keySpec; // keySpec
private IvParameterSpec ivSpec; // ivSpec
/**
* Aes256Cipher 생성자
*
* @param keyFile 파일 위치를 입력 받음
* @throws IOException 파일 io 발생하는 익셉션
* @throws InvalidKeyException key가 잘못되었을 경우 발생하는 익셉션
* @throws DecoderException 암호화된 문자열을 decoding할 발생하는 익셉션
*/
public Aes256Cipher() throws IOException, InvalidKeyException, DecoderException {
String activeProfile = (CommonUtil.nvl(System.getProperty("spring.profiles.active")));
InputStream fis = null;
String secretKey = null;
try
{
fis = new ClassPathResource("secrets/UrpSystem.keystore").getInputStream();
Properties props = new Properties();
props.load(fis);
secretKey = props.getProperty("aes256.key");
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
fis.close();
}
byte[] secretKeyBytes = Hex.decodeHex(secretKey);
if (secretKeyBytes.length != 32) {
throw new InvalidKeyException("Invalid key (key length is not valid) ");
}
byte[] ivBytes = new byte[16];
System.arraycopy(secretKeyBytes, 0, ivBytes, 0, 16);
keySpec = new SecretKeySpec(secretKeyBytes, "AES");
ivSpec = new IvParameterSpec(ivBytes);
}
/**
* encryption 하는 메소드
*
* @param plainStr 평문을 입력 받음
* @return 암호화된 문자열
*/
public String encrypt(String plainStr) {
if (plainStr == null) {
return null;
}
String encryptedStr = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plainStr.getBytes("UTF-8"));
encryptedStr = new String(Base64.encodeBase64(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
return encryptedStr;
}
/**
* 암호화된 문자열을 복호화하는 메소드
*
* @param encryptedStr 암호화된 문자열
* @return 암호화가 해제된 문자열
*/
public String decrypt(String encryptedStr) {
if (encryptedStr == null)
{
return null;
}
String decryptedStr = null;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] byteStr = Base64.decodeBase64(encryptedStr.getBytes("UTF-8"));
decryptedStr = new String(cipher.doFinal(byteStr), "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return decryptedStr;
}
}

View File

@ -0,0 +1,114 @@
package com.urpsys.baseauth.common.exception;
import java.sql.SQLSyntaxErrorException;
import lombok.Getter;
/**
* Custom exception 클래스
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
public class CustomException extends Exception
{
private static final long serialVersionUID = 3559302713942492181L;
@Getter
private String errorCode;
@Getter
private String errorMsg;
/**
* 생성자(throwable를 받아서 exception 종류에 따라 에러 코드 정의하는 클래스)
* 에러코드 처리 부분은 향후 db에서 에러코드 읽어와서 매핑하는 것으로
* 변경 가능성 있음
* @param throwable
*/
public CustomException(Throwable throwable) {
Throwable rootThrowable = getRootCause(throwable);
// TODO 에러 코드는 상세 정의해서 define 해야
if(rootThrowable instanceof SQLSyntaxErrorException) {
this.errorCode = "100";
this.errorMsg = "SQL 오류";
} else if(rootThrowable instanceof ArithmeticException) {
this.errorCode = "200";
this.errorMsg = "연산 오류";
} else {
this.errorCode = "900";
this.errorMsg = "Unknown Error";
}
}
/**
* 생성자(에러메시지만 받을 경우 에러코드를 0을 default로 세팅)
* @param errorMsg
*/
public CustomException(String errorMsg) {
super(errorMsg);
this.errorCode = "0";
this.errorMsg = errorMsg;
}
/**
* 생성자(errorcode, errmsg를 받아 세팅, 소스코드에서 편하게 사용하기 위해
* 에러코드를 int 값으로 받으면 string으로 변환하여 저장)
* @param errorCode
* @param errorMsg
*/
public CustomException(int errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = String.valueOf(errorCode);
this.errorMsg = errorMsg;
}
/**
* 생성자(에러코드, 에러메시지를 받아 세팅)
* @param errorCode
* @param errorMsg
*/
public CustomException(String errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
/**
* stack에서 에러코드 root cause를 찾아내는 메소드
* @param throwable
* @return
*/
private Throwable getRootCause(Throwable throwable) {
Throwable cause = throwable.getCause();
if (cause == null) {
return throwable;
}
while (true) {
if(cause.getCause() == null) {
break;
} else {
cause = cause.getCause();
}
}
return cause;
}
}

View File

@ -0,0 +1,90 @@
package com.urpsys.baseauth.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import com.urpsys.baseauth.domain.MemberVO;
/**
* 토큰 형태 구성 클래스
*
* @author 나혁제
* @since 2025.01.03
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.03 나혁제 최초작성
*
* </pre>
*/
public class CustomTokenEnhancer implements TokenEnhancer
{
// 필수생성
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication)
{
MemberVO memberVo = (MemberVO) authentication.getPrincipal();
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("strMEM_ID" , memberVo.getStrMEM_ID ());
additionalInfo.put("strPWD" , memberVo.getStrPWD ());
additionalInfo.put("strPWD_HINT" , memberVo.getStrPWD_HINT ());
additionalInfo.put("strPWD_RANS" , memberVo.getStrPWD_RANS ());
additionalInfo.put("strRRNO" , memberVo.getStrRRNO ());
additionalInfo.put("strMEM_NM" , memberVo.getStrMEM_NM ());
additionalInfo.put("strZIP_NO" , memberVo.getStrZIP_NO ());
additionalInfo.put("strADDR" , memberVo.getStrADDR ());
additionalInfo.put("strREGN_NO" , memberVo.getStrREGN_NO ());
additionalInfo.put("strMEM_STACD" , memberVo.getStrMEM_STACD ());
additionalInfo.put("strADDR2" , memberVo.getStrADDR2 ());
additionalInfo.put("strEND_TELNO" , memberVo.getStrEND_TELNO ());
additionalInfo.put("strMOVE_TELNO" , memberVo.getStrMOVE_TELNO ());
additionalInfo.put("strGRP_ID" , memberVo.getStrGRP_ID ());
additionalInfo.put("strMEM_FAX_NO" , memberVo.getStrMEM_FAX_NO ());
additionalInfo.put("strMEM_EML_ADDR" , memberVo.getStrMEM_EML_ADDR ());
additionalInfo.put("strMDL_TELNO" , memberVo.getStrMDL_TELNO ());
additionalInfo.put("strJOIN_DTM" , memberVo.getStrJOIN_DTM ());
additionalInfo.put("strSEX_CD" , memberVo.getStrSEX_CD ());
additionalInfo.put("strESNTL_ID" , memberVo.getStrESNTL_ID ());
additionalInfo.put("strLOCK_AT" , memberVo.getStrLOCK_AT ());
additionalInfo.put("strLOCK_NCNT" , memberVo.getStrLOCK_NCNT ());
additionalInfo.put("strLAST_CHG_DTM" , memberVo.getStrLAST_CHG_DTM ());
additionalInfo.put("strLAST_PWD_CHG_DTM", memberVo.getStrLAST_PWD_CHG_DTM());
additionalInfo.put("userSe" , memberVo.getUserSe ());
additionalInfo.put("orgnztId" , memberVo.getOrgnztId ());
additionalInfo.put("uniqId" , memberVo.getUniqId ());
additionalInfo.put("userName" , memberVo.getStrMEM_NM ());
additionalInfo.put("strLastConnectTime" , memberVo.getStrLastConnectTime ());
// 문자열로 변환 처리후 전송
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
String strAuthority = "";
for(GrantedAuthority grAuth : memberVo.getAuthorities())
{
strAuthority = grAuth.getAuthority()+"-";
}
additionalInfo.put("authorities", strAuthority);
((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}

View File

@ -0,0 +1,38 @@
package com.urpsys.baseauth.config;
import java.io.IOException;
import java.security.InvalidKeyException;
import org.apache.commons.codec.DecoderException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.urpsys.baseauth.common.crypto.Aes256Cipher;
/**
* 암호화 유틸리티를 등록하는 클래스
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Configuration
public class EncryptConfig
{
@Bean(name="aes256Cipher")
public Aes256Cipher aes256Cipher() throws InvalidKeyException, IOException, DecoderException
{
return new Aes256Cipher();
}
}

View File

@ -0,0 +1,206 @@
package com.urpsys.baseauth.config;
import java.util.Arrays;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import com.urpsys.baseauth.common.crypto.Aes256Cipher;
import com.urpsys.baseauth.service.UserDetailService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
/**
* 인증서버 기본세팅
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
* @comment :
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Slf4j
@EnableAuthorizationServer
@Configuration
public class Oauth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter
{
@Autowired
private UserDetailService userDetailService;
@Autowired
private AuthenticationManager authenticationManager;
/* DB 접속정보 */
@Autowired
private DataSource dataSource;
/* 환경정보 */
@Autowired
private Environment env;
/* aes256 암호화 유틸리티 */
@Autowired
private Aes256Cipher aes256Cipher;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 인증허용범위 설정 (5번 설정등록)
*
* @param 인증 범위 객체
* @return 인증 범위 상세객체
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
{
log.info(">>>>>>>>>> 5. Oauth2AuthorizationConfig | AuthorizationServerSecurityConfigurer | configure | 허용범위설정 <<<<<<<<<<");
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients()
;
log.info("<<<<<<<<<< 5. Oauth2AuthorizationConfig | AuthorizationServerSecurityConfigurer | configure | 허용범위설정 >>>>>>>>>>");
}
/**
* 접근 client 설정 (4번 설정등록)
*
* @param 클라이언트 접근정보 객체
* @return 클라이언트 접근정보 상세 객체
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
{
log.info(">>>>>>>>>> 4. Oauth2AuthorizationConfig | ClientDetailsServiceConfigurer | configure | 접근 클라이언트 설정 <<<<<<<<<<");
clients.inMemory()
.withClient("clientId")
.secret(passwordEncoder.encode("secretKey"))
.authorizedGrantTypes("authorization_code","password", "refresh_token", "client_credentials") // 가능한 토큰 발행 타입
.scopes("read", "write") // 가능한 접근 범위
.accessTokenValiditySeconds (60*60*24) // access 토큰 유효 시간 : 24시간
.refreshTokenValiditySeconds(60*60*24) // refresh 토큰 유효 시간 : 24시간
.redirectUris("http://localhost:9010/callback") // 가능한 redirect uri
.autoApprove(true); // 권한 동의는 자동으로 yes (false 할시 권한 동의 여부를 묻는다.)
log.info("<<<<<<<<<< 4. Oauth2AuthorizationConfig | ClientDetailsServiceConfigurer | configure | 접근 클라이언트 설정 >>>>>>>>>>");
}
/**
* 인증, 토큰유형, 토큰발행처리등 토큰발행정보설정 (3번 설정등록)
*
* @param 인증,토큰정보 객체
* @return 인증,토큰정보 상세객체
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
log.info(">>>>>>>>>> 3. Oauth2AuthorizationConfig | AuthorizationServerEndpointsConfigurer | configure | 인증, 토큰 설정 <<<<<<<<<<");
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), jwtAccessTokenConverter())); // 토큰 enhancer 객체 생성
endpoints.authenticationManager(authenticationManager) // grant_type password를 사용하기 위함
// (manager 지정 안할시 password type 으로 토큰 발행시 Unsupported grant type: password 오류 발생)
.userDetailsService(userDetailService) // refrash token 발행시 유저 정보 검사 하는데 사용하는 서비스 설정
.tokenEnhancer(tokenEnhancerChain) // enhancer 설정
.accessTokenConverter(jwtAccessTokenConverter())
.approvalStore(approvalStore())
;
log.info("<<<<<<<<<< 3. Oauth2AuthorizationConfig | AuthorizationServerEndpointsConfigurer | configure | 인증, 토큰 설정 >>>>>>>>>>");
}
// 토큰 DB 저장
public HikariDataSource datasource2()
{
HikariConfig config = new HikariConfig();
String dataSourceName = "primarydb";
config.setDriverClassName (env.getProperty(dataSourceName + ".driverClassName" ));
config.setJdbcUrl (env.getProperty(dataSourceName + ".jdbcUrl" ));
config.setUsername (aes256Cipher.decrypt(env.getProperty(dataSourceName + ".username")));
config.setPassword (aes256Cipher.decrypt(env.getProperty(dataSourceName + ".password")));
return new HikariDataSource(config);
}
// 토큰 DB 저장
@Bean
public TokenStore tokenStore()
{
DataSource ds2 = datasource2();
return new JdbcTokenStore(ds2);
}
// 권한 동의 DB 저장
@Bean
public ApprovalStore approvalStore()
{
DataSource ds2 = datasource2();
return new JdbcApprovalStore(ds2);
}
/**
* 자바토큰 발행 암호와 처리
*
* @param 인증,토큰정보 객체
* @return 인증,토큰정보 상세객체
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter()
{
// RSA 암호화 : 대칭키 암호화 : 공개키로 암호화 하면 개인키로 복호화
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwtkey.jks"), "corin1234".toCharArray());
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwtkey"));
return converter;
}
}

View File

@ -0,0 +1,77 @@
package com.urpsys.baseauth.config;
import java.util.Base64;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
/**
* 패스워드 암호화 정책 수립(접근 Client, 회원비미번호)
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
* @comment : PasswordEncoder는 SpringSecurity5 이상에서는 필수 생성 처리
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
//
@Slf4j
@Configuration
public class PasswordEncoderConfig
{
@Bean
public PasswordEncoder passwordEncoder()
{
// 1번설정
log.info(">>>>>>>>>> 1. WebSecurityConfiguration passwordEncoder <<<<<<<<<<");
return new BCryptPasswordEncoder()
{
/**
* 입력정보을 암호화 하여 일치여부 확인
*
* @param 입력pass, 등록pass
* @return 일치여부
*/
@Override
public boolean matches(CharSequence rawPassword
, String encodedPassword)
{
log.info(">>>>>>>>>> WebSecurityConfiguration BCryptPasswordEncoder matches <<<<<<<<<<");
log.info("입력 rawPassword => {}", rawPassword );
log.info("DB encodedPassword => {}", encodedPassword );
log.info("변환 password => {}", super.encode(rawPassword) ); // 양방향 암호화 정책으로 print 부분이 다름
if (super.matches(rawPassword, encodedPassword))
{
log.info("===> password match ");
return true;
}
else
{
log.info("===> password not match ");
return false;
}
}
};
}
}

View File

@ -0,0 +1,113 @@
package com.urpsys.baseauth.config;
import java.io.IOException;
import java.sql.Connection;
import javax.sql.DataSource;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.urpsys.baseauth.common.DataSourceUtil;
import com.urpsys.baseauth.common.crypto.Aes256Cipher;
import com.urpsys.baseauth.common.exception.CustomException;
/**
* primary db config 클래스
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Configuration
@EnableTransactionManagement
@MapperScan(value="com.urpsys.baseauth.dao", sqlSessionFactoryRef="primarySqlSessionFactory")
public class PrimaryDbConfig
{
/* spring environment class */
@Autowired
private Environment env;
/* aes256 암호화 유틸리티 */
@Autowired
private Aes256Cipher aes256Cipher;
/**
* 데이터소스 등록하는 메소드
* @return
*/
@Bean(name="primaryDataSource")
public DataSource primaryDataSource()
{
return new LazyConnectionDataSourceProxy(DataSourceUtil.createDataSource("primarydb", env, aes256Cipher));
}
/**
* sqlsessionfactory 등록하는 메소드
*
* @param dataSource
* @param context
* @return
* @throws SchedulerException
* @throws IOException
*/
@Bean(name="primarySqlSessionFactory")
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource, ApplicationContext context)
throws CustomException, IOException
{
SqlSessionFactory sqlSessionFactory = DataSourceUtil.createSqlSessionFactory( dataSource
, context.getResource ("classpath:mapper/primarydb/config/MybatisConfig.xml")
, context.getResources("classpath:mapper/primarydb/sqlmap/**/*Mapper*.xml")
);
sqlSessionFactory.getConfiguration().setDefaultExecutorType(ExecutorType.SIMPLE);
return sqlSessionFactory;
}
/**
* sqlsessiontemplate 등록하는 메소드
* @param primarySqlSessionFactory
* @return
*/
@Bean("primarySqlSessionTemplate")
public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory primarySqlSessionFactory)
{
return new SqlSessionTemplate(primarySqlSessionFactory);
}
/**
* 트랜잭션 매니저 등록하는 메소드
* @param dataSource
* @return
*/
@Bean(name="primaryTxManager")
public PlatformTransactionManager primaryTxManager(@Qualifier("primaryDataSource") DataSource dataSource)
{
return DataSourceUtil.createTxManager(dataSource);
}
}

View File

@ -0,0 +1,116 @@
package com.urpsys.baseauth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.urpsys.baseauth.inner.handler.CustomFailHandler;
import com.urpsys.baseauth.inner.handler.CustomSuccessHandler;
import com.urpsys.baseauth.inner.provider.CustomAuthenticationProvider;
import lombok.extern.slf4j.Slf4j;
/**
* 웹설정에 스프링시큐리티 기본세팅
*
* @author 나혁제
* @since 2023.02.28
* @version 1.0.0
* @see
* @comment :
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Slf4j
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
/**
* 서버보안 설정 (6번 설정등록)
*
* @param 웹서버 보안객체
* @return 웹서버 보안 상세 객체
*/
@Override
protected void configure(HttpSecurity http) throws Exception
{
log.info(">>>>>>>>>> SecurityConfig | HttpSecurity | configure | 서버보안설정 <<<<<<<<<<");
http.csrf().disable() // csrf 공격을 막기 위해 state 값을 전달 받지 않는다
.formLogin() // 기본 제공하는 로그인 화면 사용
.loginPage("/oauth/login") // 커스텀 로그인 페이지 설정
.failureHandler(failureHandler()) // 로그인 실패 custom
.successHandler(successHandler()) // 로그인 성공 custom
.and()
.httpBasic(); // http 통신으로 basic auth를 사용 있다. (ex: Authorization: Basic bzFbdGfmZrptWY30YQ==)
log.info("<<<<<<<<<< SecurityConfig | HttpSecurity | configure | 서버보안설정 >>>>>>>>>>");
}
/**
* authenticationManager bean 생성 하여 셋팅 안할시 grant_type : password 지원 안함
* @return
* @throws Exception
*/
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception
{
return super.authenticationManager();
}
/**
* 사용자를 인증하는 방법이 담긴 객체 (2번 설정등록)
*
* @param 인증객체
* @return 상세인증처리 방법 세팅
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
// 2번 설정등록
log.info(">>>>>>>>>> 2.SecurityConfig configure AuthenticationManagerBuilder <<<<<<<<<<");
auth.authenticationProvider(customAuthenticationProvider);
log.info("<<<<<<<<<< 2.SecurityConfig configure AuthenticationManagerBuilder >>>>>>>>>>");
}
@Bean
public AuthenticationFailureHandler failureHandler()
{
return new CustomFailHandler();
}
@Bean
public AuthenticationSuccessHandler successHandler()
{
return new CustomSuccessHandler();
}
}

View File

@ -0,0 +1,48 @@
package com.urpsys.baseauth.dao;
import java.util.LinkedHashMap;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.urpsys.baseauth.domain.MemberVO;
/**
* 회원정보 추출 Mapper
*
* @author urp 인프라본부 나혁제
* @since 2025.01.23
* @version 1.0.0
* @see
* @comment :
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.23 나혁제 최초작성
*
* </pre>
*/
@Mapper
@Repository
public interface MemberDao
{
public MemberVO actionLogin(String strId); // 회원정보 추출
// 최종접속시간 획득
public String getLastConnectTime(String strUniqId);
// 회원 lock 정보 확인
public LinkedHashMap<String, Object> selectLoginIncorrect(String strId);
// 회원 lock Count 처리
public int updateLoginLockAdd(String strId);
// 회원 lock 해제 처리
public int updateLoginLockCancel(String strId);
}

View File

@ -0,0 +1,171 @@
package com.urpsys.baseauth.domain;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
import lombok.Data;
/**
* 사용자 정보 VO
*
* @author 나혁제
* @since 2025.01.03
* @version 1.0.0
* @see
* @comment : UserDetails 상속처리해야 userDetailService 사용가능
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.03 나혁제 최초작성
*
* </pre>
*/
@Data
public class MemberVO extends TbGnlMemInfoVO implements UserDetails
{
/**
*
*/
private String login;
private String passwordHash;
private Set<GrantedAuthority> authorities; // 계정이 가지고 있는 권한 목록
public void setAuthorities(Collection<? extends GrantedAuthority> authorities)
{
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities)
{
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
// Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-717)
SortedSet<GrantedAuthority> sortedAuthorities =
new TreeSet<GrantedAuthority>(new AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities)
{
Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
return sortedAuthorities;
}
/**
* Returns the authorities granted to the user(필수)
*
* @return 웹서버 보안 상세 객체
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
{
return authorities;
}
/**
* Returns the password used to authenticate the user(필수)
*
* @return 패스워드
*/
@Override
public String getPassword()
{
return this.passwordHash;
}
/**
* Returns the username used to authenticate the user.(필수)
*
* @return ID
*/
@Override
public String getUsername()
{
return this.login;
}
/**
* Indicates whether the user's account has expired.(필수)
*
* @return id 만료여부
*/
@Override
public boolean isAccountNonExpired()
{
return true;
}
/**
* Indicates whether the user is locked or unlocked.(필수)
*
* @return id 잠금여부
*/
@Override
public boolean isAccountNonLocked()
{
return true;
}
/**
* Indicates whether the user's credentials (password) has expired.(필수)
*
* @return password 잠금여부
*/
@Override
public boolean isCredentialsNonExpired()
{
return true;
}
/**
* Indicates whether the user is enabled or disabled.(필수)
*
* @return ID 사용여부
*/
@Override
public boolean isEnabled()
{
return true;
}
private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable
{
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public int compare(GrantedAuthority g1, GrantedAuthority g2)
{
// Neither should ever be null as each entry is checked before adding it to the set.
// If the authority is null, it is a custom authority and should precede others.
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}
}

View File

@ -0,0 +1,59 @@
package com.urpsys.baseauth.domain;
import lombok.Data;
/**
* 사용자 정보 VO
*
* @author 나혁제
* @since 2025.01.03
* @version 1.0.0
* @see
* @comment : UserDetails 상속처리해야 userDetailService 사용가능
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.03 나혁제 최초작성
*
* </pre>
*/
@Data
public class TbGnlMemInfoVO
{
private String strMEM_ID;
private String strPWD;
private String strPWD_HINT;
private String strPWD_RANS;
private String strRRNO;
private String strMEM_NM;
private String strZIP_NO;
private String strADDR;
private String strREGN_NO;
private String strMEM_STACD;
private String strADDR2;
private String strEND_TELNO;
private String strMOVE_TELNO;
private String strGRP_ID;
private String strMEM_FAX_NO;
private String strMEM_EML_ADDR;
private String strMDL_TELNO;
private String strJOIN_DTM;
private String strSEX_CD;
private String strESNTL_ID;
private String strLOCK_AT;
private String strLOCK_NCNT;
private String strLAST_CHG_DTM;
private String strLAST_PWD_CHG_DTM;
private String userSe;
private String orgnztId;
private String uniqId;
private String strAuthCd;
private String strLastConnectTime;
}

View File

@ -0,0 +1,69 @@
package com.urpsys.baseauth.inner.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import lombok.extern.slf4j.Slf4j;
/**
* 회원인증 실패시 처리 handler
*
* @author urp 인프라본부 나혁제
* @since 2025.01.23
* @version 1.0.0
* @see
* @comment :
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Slf4j
public class CustomFailHandler extends SimpleUrlAuthenticationFailureHandler
{
/**
* 회원인증 실패시 처리
*
* @param HttpServletRequest
* , HttpServletResponse
* , AuthenticationException // 실패 Exception
* @return
* @throw
*/
@Override
public void onAuthenticationFailure(HttpServletRequest request
, HttpServletResponse response
, AuthenticationException exception) throws IOException, ServletException
{
log.debug(">>>>>>>>>> CustomFailHandler onAuthenticationFailure <<<<<<<<<<");
log.error("exception 메세지 확인 => {}", exception.getMessage());
exception.printStackTrace();
if(exception instanceof UsernameNotFoundException)
{
log.error("### => {}", exception.getMessage());
response.sendRedirect("http://localhost:9010/oauth/login?error="+exception.getMessage());
}
log.debug("<<<<<<<<<< CustomFailHandler onAuthenticationFailure >>>>>>>>>>");
}
}

View File

@ -0,0 +1,51 @@
package com.urpsys.baseauth.inner.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import lombok.extern.slf4j.Slf4j;
/**
* 회원인증 성공시 처리 handler
*
* @author urp 인프라본부 나혁제
* @since 2025.01.23
* @version 1.0.0
* @see
* @comment :
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2023.02.28 나혁제 최초작성
*
* </pre>
*/
@Slf4j
public class CustomSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler
{
@Override
public void onAuthenticationSuccess(HttpServletRequest request
, HttpServletResponse response
, Authentication authentication) throws ServletException, IOException
{
log.debug(">>>>>>>>>> CustomSuccessHandler onAuthenticationSuccess <<<<<<<<<<");
log.info("### login success => {}", authentication.getAuthorities());
super.onAuthenticationSuccess(request, response, authentication);
log.debug("<<<<<<<<<< CustomSuccessHandler onAuthenticationSuccess >>>>>>>>>>");
}
}

View File

@ -0,0 +1,127 @@
package com.urpsys.baseauth.inner.provider;
import java.util.LinkedHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import com.urpsys.baseauth.service.UserDetailService;
import lombok.extern.slf4j.Slf4j;
/**
* Urp 기본 회원 인증수행처리
*
* @author urp 인프라본부 나혁제
* @since 2025.01.23
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.23 나혁제 최초작성
*
* </pre>
*/
@Slf4j
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider
{
@Autowired
private UserDetailService userDetailService;
@Autowired
PasswordEncoder passwordEncoder;
/**
* 인증수행처리(필수생성)
*
* @param 인증 입력정보
* @return 인증정보
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
log.info(">>>>>>>>>> CustomAuthenticationProvider authenticate <<<<<<<<<<");
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
// 사용자 Lock 체크
LinkedHashMap<String, Object> returnMap = userDetailService.selectLoginIncorrect(username);
// 해당 회원 ID Lock 상태
if(returnMap != null)
{
log.info(" 확인해보자 => {}", returnMap.toString());
if(returnMap.get("lockAt") != null && returnMap.get("lockAt").equals("Y"))
{
throw new UsernameNotFoundException("-1:id is locked");
}
}
log.info("## => username:{} | password:{} ", username, password);
log.info("## => 또다른 정보1 : [{}] ", authentication.getDetails());
log.info("## => 또다른 정보2 : [{}] ", authentication.toString());
UserDetails info = userDetailService.loadUserByUsername(username); // 사용자 정보 추출
if(ObjectUtils.isEmpty(info))
{
throw new UsernameNotFoundException("-2:user not found");
}
// 패스워드 일치 여부 확인
log.info("입력 username => {} ", username);
log.info("입력 password => {} ", password);
log.info("입력 변환 password => {} ", passwordEncoder.encode(password));
if (passwordEncoder.matches(password, info.getPassword()))
{
log.debug("패스워드 일치");
userDetailService.updateLoginLockCancel(username); // lock count 해제
}
else
{
log.debug("패스워드 불일치");
userDetailService.updateLoginLockAdd(username); // lock count 추가
throw new UsernameNotFoundException("-3:please password check");
}
log.error("## => {}", info.getAuthorities());
log.info("<<<<<<<<<< CustomAuthenticationProvider authenticate >>>>>>>>>>");
// principal 정보는 jwt 토큰 생성시 추가정보 넣는데 사용하오니 필요한 정보는 여기서 넣어주세요.
return new UsernamePasswordAuthenticationToken(info, password, info.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication)
{
log.debug(">>>>>>>>>> CustomAuthenticationProvider supports <<<<<<<<<<");
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

View File

@ -0,0 +1,108 @@
package com.urpsys.baseauth.service;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.LinkedHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
// import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.urpsys.baseauth.dao.MemberDao;
import com.urpsys.baseauth.domain.MemberVO;
/**
* 회원정보 추출 서비스
*
* @author urp 인프라본부 나혁제
* @since 2025.01.23
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.23 나혁제 최초작성
*
* </pre>
*/
@Slf4j
@Service
public class UserDetailService implements UserDetailsService
{
@Autowired
private MemberDao memberDao;
/**
* 회원정보 추출
* 필수생성
*/
@Override
public UserDetails loadUserByUsername(String strUserId) throws UsernameNotFoundException
{
log.info(">>>>>>>>>> UserDetailService loadUserByUsername <<<<<<<<<<");
log.info("strUserId=>{}", strUserId);
MemberVO memberVo = memberDao.actionLogin(strUserId);
if(memberVo == null)
{
log.info("사용자가 존재하지 않음");
}
else
{
memberVo.setPasswordHash(memberVo.getStrPWD());
memberVo.setLogin(memberVo.getStrMEM_ID());
// memberVo.setAuthorities (Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
memberVo.setAuthorities (Arrays.asList(new SimpleGrantedAuthority( memberVo.getStrAuthCd() )));
log.info("memberVo getPASSWORD_HASH =>{}", memberVo.getPasswordHash());
log.info("memberVo getPassword =>{}", memberVo.getPassword());
log.info("memberVo getlogin =>{}", memberVo.getLogin());
// 최종접속시간 추가
String strLastConnectTime = memberDao.getLastConnectTime(memberVo.getUniqId());
memberVo.setStrLastConnectTime(strLastConnectTime);
}
log.info("<<<<<<<<<< UserDetailService loadUserByUsername >>>>>>>>>>");
return memberVo;
}
// 회원 lock 정보 확인
public LinkedHashMap<String, Object> selectLoginIncorrect(String strId)
{
return memberDao.selectLoginIncorrect(strId);
}
// 회원 lock Count 처리
public int updateLoginLockAdd(String strId)
{
return memberDao.updateLoginLockAdd(strId);
}
// 회원 lock 해제 처리
public int updateLoginLockCancel(String strId)
{
return memberDao.updateLoginLockCancel(strId);
}
}

View File

@ -0,0 +1,81 @@
package com.urpsys.baseauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.urpsys.baseauth.common.CommonUtil;
/**
* 인증서버 기본 실행 클래스
*
* @author 나혁제
* @since 2025.01.02
* @version 1.0.0
* @see
*
* <pre>
*
* << 개정이력(Modification information) >>
*
* 수정일 수정자 수정내용
* ----------- --------- ------------------------
* 2025.01.02 나혁제 최초작성
*
* </pre>
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.urpsys.baseauth"})
public class urpBaseAuthApplication
{
public static void main(String[] args)
{
String activeProfile = (CommonUtil.nvl(System.getProperty("spring.profiles.active")));
if(activeProfile.equals("local"))
{
System.out.println("################################################");
System.out.println("############# local Env ########################");
System.out.println("################################################");
}
else if(activeProfile.equals("hpnote"))
{
System.out.println("################################################");
System.out.println("############# hpnote Env ########################");
System.out.println("################################################");
}
else if(activeProfile.equals("vmware"))
{
System.out.println("################################################");
System.out.println("############# vmware Env ########################");
System.out.println("################################################");
}
else if(activeProfile.equals("infra_server"))
{
System.out.println("################################################");
System.out.println("############# infra_server Env #################");
System.out.println("################################################");
}
else if(activeProfile.equals("kic_dev"))
{
System.out.println("################################################");
System.out.println("############# kic_dev Env ######################");
System.out.println("################################################");
}
else if(activeProfile.equals("kic_rel"))
{
System.out.println("################################################");
System.out.println("############# kic_rel Env ######################");
System.out.println("################################################");
}
else
{
System.out.println("################################################");
System.out.println("############# No Define ########################");
System.out.println("################################################");
}
SpringApplication.run(urpBaseAuthApplication.class, args);
}
}

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://109.26.11.21:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.10.10.203:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 12000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.10.10.203:3306/ur_itms_rel_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: YvRZ5jyhmB6gwVSUGBOqNMQB00k6OZZSfUH5ZU4GEFs=
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,38 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
# jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.138:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

View File

@ -0,0 +1,37 @@
# Service port
server:
port: 11000
# JPA 설정, JSP 설정
spring:
devtools:
livereload:
enabled: true
# Primary db information
primarydb:
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
jdbcUrl: jdbc:log4jdbc:mariadb://192.168.8.131:3306/ur_itms_db?characterEncoding=UTF-8&serverTimezone=Asia/Seoul&rewriteBatchedStatements=true
username: g9IwFesTyIloXVpUnfOX0g==
password: E4SOtjDqqO79BQERc/eaTw==
maximumPoolSize: 35
minimumIdle: 2
connectionTimeout: 3000
idleTimeout: 300000
testOnBorrow: true
validationQuery: SELECT 1
# SQL Log 관련 setting
log4jdbc:
spylogdelegator:
name: net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
dump:
sql:
maxlinelength: 0
logging.level.jdbc.sqlonly: info
logging.level.jdbc.sqltiming: false
logging.level.jdbc.audit: false
logging.level.jdbc.resultset: false
logging.level.jdbc.resultsettable: info
logging.level.jdbc.connection: false

Binary file not shown.

View File

@ -0,0 +1,2 @@
log4jdbc.spylogdelegator.name = net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
log4jdbc.dump.sql.maxlinelength=0

View File

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<contextName>${HOSTNAME}</contextName>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
</appender>
<!--
<root level="error">
<appender-ref ref="consoleAppender" />
</root>
<logger name="TRACE_LOGGER" level="error" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
-->
<root level="info">
<appender-ref ref="consoleAppender" />
</root>
<logger name="TRACE_LOGGER" level="info" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
<!-- 일단 사용하지 않음 -->
<!--
<property name="LOG_DIR" value="/var/log/LAMP" />
<springProfile name="!local">
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>
</encoder>
<file>${LOG_DIR}/${HOSTNAME}_server.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${HOSTNAME}_server.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>10</maxHistory>
</rollingPolicy>
</appender>
<appender name="asyncAppender" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>10000</queueSize>
<appender-ref ref="rollingFileAppender" />
</appender>
<appender name="traceRollingFileAppend" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%msg%n</Pattern>
</encoder>
<file>${LOG_DIR}/${HOSTNAME}_trace.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/${HOSTNAME}_trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>200MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>10</maxHistory>
</rollingPolicy>
</appender>
<appender name="traceLogAppend" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>10000</queueSize>
<appender-ref ref="traceRollingFileAppend" />
</appender>
<root level="info">
<appender-ref ref="asyncAppender" />
</root>
<logger name="TRACE_LOGGER" level="info" additivity="false">
<appender-ref ref="traceLogAppend" />
</logger>
</springProfile>
-->
</Configuration>

View File

@ -0,0 +1,4 @@
ows.log.path=C://ode/logs/was
ows.log.level=debug
ows.log.filename=ows_adm_log
ows.log.err.filename=ows_adm_log_error

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="defaultStatementTimeout" value="1800"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="defaultFetchSize" value="1000" />
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
-->
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="defaultStatementTimeout" value="1800"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="defaultFetchSize" value="1000" />
<setting name="mapUnderscoreToCamelCase" value="false"/>
</settings>
<typeAliases>
<typeAlias alias="MemberVO" type="com.urpsys.baseauth.domain.MemberVO" />
</typeAliases>
<!--
<typeAliases>
<typeAlias alias="UserVO" type="com.gdsc.ImgEd.domain.UserVO" />
<typeAlias alias="ImageInfoVO" type="com.gdsc.ImgEd.domain.ImageInfoVO" />
<typeAlias alias="ImageMetaVO" type="com.gdsc.ImgEd.domain.ImageMetaVO" />
<typeAlias alias="IspnMngInfoVO" type="com.gdsc.ImgEd.domain.IspnMngInfoVO" />
<typeAlias alias="IspnMngInfo2VO" type="com.gdsc.ImgEd.domain.IspnMngInfo2VO" />
<typeAlias alias="IspnMngInfo4VO" type="com.gdsc.ImgEd.domain.IspnMngInfo4VO" />
<typeAlias alias="IspnMngInfo5VO" type="com.gdsc.ImgEd.domain.IspnMngInfo5VO" />
</typeAliases>
-->
</configuration>

View File

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.urpsys.baseauth.dao.MemberDao">
<select id="actionLogin" parameterType="string" resultType="MemberVO">
<![CDATA[
SELECT A.USER_ID AS strMEM_ID
, A.USER_NM AS strMEM_NM
, '' AS strRRNO
, A.PASSWORD AS strPWD
, A.USER_EMAIL AS strMEM_EML_ADDR
, A.USER_SE AS userSe
, A.ORGNZT_ID AS orgnztId
, A.GROUP_ID AS strGRP_ID
, A.ESNTL_ID AS strESNTL_ID
, A.ESNTL_ID AS uniqId
, B.AUTH_CD AS strAuthCd
FROM COMVNUSERMASTER A
, TB_USER_CRYP_CNF B
WHERE A.USER_ID = #{loginId}
AND A.ESNTL_ID = B.CRYP_CNF_TRG_ID
]]>
</select>
<select id="getLastConnectTime" parameterType="string" resultType="string">
<![CDATA[
SELECT DATE_FORMAT ( IFNULL(MAX(CRT_DTM), NOW()), '%Y-%m-%d %H:%i:%s')
FROM TB_ACES_LOG
WHERE ACES_ID = #{uniqId}
]]>
</select>
<!-- 로그인인증제한 조회 -->
<select id="selectLoginIncorrect" parameterType="string" resultType="java.util.LinkedHashMap">
SELECT TASK_USER_ID AS userId
, PWD AS userPw
, USER_NM AS userNm
, ESNTL_ID AS uniqId
, IFNULL(LOCK_AT,'N') AS lockAt
, IFNULL(LOCK_NCNT,0) AS lockNcnt
FROM TB_TASK_USER_INFO
WHERE TASK_USER_ID = #{id}
</select>
<update id="updateLoginLockAdd" parameterType="string" >
UPDATE TB_TASK_USER_INFO
SET LOCK_AT = CASE WHEN LOCK_NCNT > 1 THEN 'Y'
ELSE ''
END
, LOCK_NCNT = IFNULL(LOCK_NCNT,0)+1
, LAST_CHG_DTM = sysdate()
WHERE TASK_USER_ID = #{id}
</update>
<update id="updateLoginLockCancel" parameterType="string" >
UPDATE TB_TASK_USER_INFO
SET LOCK_AT = NULL
, LOCK_NCNT = NULL
, LAST_CHG_DTM = sysdate()
WHERE TASK_USER_ID = #{id}
</update>
</mapper>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gdsc.ImgEd.dao.UserDao">
<select id="imageMetaBackup" parameterType="string" resultType="string">
<![CDATA[
select '1'
]]>
</select>
</mapper>

View File

@ -0,0 +1 @@
aes256.key=52f48aa1c7435bc11bf909d9d7d1d5932f4bacd8184ec5c1eed6d03ee17fe126

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<!-- main -->
<definition name="main-layout" template="/WEB-INF/jsp/tilesLayout/base-main.jsp">
<put-attribute name="header" value="/WEB-INF/jsp/tilesLayout/header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/jsp/tilesLayout/footer.jsp" />
</definition>
<definition name="tiles/*" extends="main-layout">
<put-attribute name="body" value="/WEB-INF/jsp/{1}.jsp" />
</definition>
<definition name="tiles/*/*" extends="main-layout">
<put-attribute name="body" value="/WEB-INF/jsp/{1}/{2}.jsp" />
</definition>
<definition name="tiles/*/*/*" extends="main-layout">
<put-attribute name="body" value="/WEB-INF/jsp/{1}/{2}/{3}.jsp" />
</definition>
</tiles-definitions>