Merge pull request #39 from Chung10Kr/contribution-018

Apply Spring Security, Implement JwtAuthenticationFilter, Remove Duplicate Token Authentication Code
main
eGovFrameSupport 2 years ago committed by GitHub
commit 4564a608ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -71,15 +71,27 @@
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<scope>provided</scope>
</dependency>

@ -1,5 +1,7 @@
package egovframework.com.cmm;
import egovframework.com.cmm.service.ResultVO;
import java.util.regex.Pattern;
/**
@ -18,6 +20,14 @@ import java.util.regex.Pattern;
*/
public class EgovWebUtil {
public static ResultVO handleAuthError(int code, String msg) {
ResultVO resultVO = new ResultVO();
resultVO.setResultCode(code);
resultVO.setResultMessage(msg);
return resultVO;
}
public static String clearXSSMinimum(String value) {
if (value == null || value.trim().equals("")) {
return "";

@ -3,8 +3,8 @@ package egovframework.com.cmm.service.impl;
import java.util.List;
import egovframework.com.cmm.service.EgovUserDetailsService;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
/**

@ -1,15 +1,13 @@
package egovframework.com.cmm.util;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import egovframework.com.cmm.LoginVO;
import org.egovframe.rte.fdl.string.EgovObjectUtil;
/**
* EgovUserDetails Helper
*
@ -36,8 +34,8 @@ public class EgovUserDetailsHelper {
* @return Object - ValueObject
*/
public static Object getAuthenticatedUser() {
return (LoginVO)RequestContextHolder.currentRequestAttributes().getAttribute("LoginVO", RequestAttributes.SCOPE_SESSION)==null ?
new LoginVO() : (LoginVO) RequestContextHolder.currentRequestAttributes().getAttribute("LoginVO", RequestAttributes.SCOPE_SESSION);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (LoginVO) authentication.getPrincipal();
}
@ -47,14 +45,8 @@ public class EgovUserDetailsHelper {
* @return List -
*/
public static List<String> getAuthorities() {
List<String> listAuth = new ArrayList<String>();
if (EgovObjectUtil.isNull(RequestContextHolder.currentRequestAttributes().getAttribute("LoginVO", RequestAttributes.SCOPE_SESSION))) {
// log.debug("## authentication object is null!!");
return null;
}
return listAuth;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
}
/**
@ -62,10 +54,7 @@ public class EgovUserDetailsHelper {
* @return Boolean - (TRUE / FALSE)
*/
public static Boolean isAuthenticated() {
if (EgovObjectUtil.isNull(RequestContextHolder.currentRequestAttributes().getAttribute("LoginVO", RequestAttributes.SCOPE_SESSION))) {
// log.debug("## authentication object is null!!");
return Boolean.FALSE;
}
return Boolean.TRUE;
return EgovUserDetailsHelper.getAuthenticatedUser()!=null? Boolean.TRUE : Boolean.FALSE ;
}
}

@ -15,7 +15,6 @@ import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.EgovFileMngService;
import egovframework.com.cmm.service.FileVO;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.jwt.config.JwtVerification;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
@ -44,11 +43,7 @@ public class EgovFileMngApiController {
@Resource(name = "EgovFileMngService")
private EgovFileMngService fileService;
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
/** 암호화서비스 */
@Resource(name="egovARIACryptoService")
EgovCryptoService cryptoService;
@ -82,15 +77,11 @@ public class EgovFileMngApiController {
//Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
if (jwtVerification.isVerification(request)) {
fileService.deleteFileInf(fileVO);
resultVO.setResultCode(200);
resultVO.setResultMessage("삭제 성공");
} else {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
}
fileService.deleteFileInf(fileVO);
resultVO.setResultCode(200);
resultVO.setResultMessage("삭제 성공");
//--------------------------------------------
// contextRoot가 있는 경우 제외 시켜야 함

@ -1,6 +1,8 @@
package egovframework.com.jwt.config;
package egovframework.com.jwt;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -27,18 +29,21 @@ public class EgovJwtTokenUtil implements Serializable{
public static final String SECRET_KEY = EgovProperties.getProperty("Globals.jwt.secret");
//retrieve username from jwt token
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
public String getUserIdFromToken(String token) {
Claims claims = getClaimFromToken(token);
return claims.get("id").toString();
}
//retrieve expiration date from jwt token
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
public String getUserSeFromToken(String token) {
Claims claims = getClaimFromToken(token);
return claims.get("userSe").toString();
}
public String getInfoFromToken(String type, String token) {
Claims claims = getClaimFromToken(token);
return claims.get(type).toString();
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
public Claims getClaimFromToken(String token) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
return claims;
}
//for retrieveing any information from token we will need the secret key
@ -46,39 +51,32 @@ public class EgovJwtTokenUtil implements Serializable{
log.debug("===>>> secret = "+SECRET_KEY);
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
//check if the token has expired
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
//generate token for user
public String generateToken(LoginVO loginVO) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, loginVO.getUserSe()+loginVO.getId());
return doGenerateToken(loginVO, "Authorization");
}
public String generateToken(LoginVO loginVO, Map<String, Object> claims) {
return doGenerateToken(claims, loginVO.getUserSe()+loginVO.getId());
}
//while creating the token -
//1. Define claims of the token, like Issuer, Expiration, Subject, and the ID
//2. Sign the JWT using the HS512 algorithm and secret key.
//3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1)
// compaction of the JWT to a URL-safe string
private String doGenerateToken(Map<String, Object> claims, String subject) {
private String doGenerateToken(LoginVO loginVO, String subject) {
Map<String, Object> claims = new HashMap<>();
claims.put("id", loginVO.getId() );
claims.put("name", loginVO.getName() );
claims.put("userSe", loginVO.getUserSe() );
claims.put("orgnztId", loginVO.getOrgnztId() );
claims.put("uniqId", loginVO.getUniqId() );
claims.put("type", subject);
log.debug("===>>> secret = "+SECRET_KEY);
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact();
}
//validate token
public Boolean validateToken(String token, LoginVO loginVO) {
final String username = getUsernameFromToken(token);
return (username.equals(loginVO.getUserSe()+loginVO.getId()) && !isTokenExpired(token));
}
}

@ -0,0 +1,53 @@
package egovframework.com.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import egovframework.com.cmm.EgovWebUtil;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* fileName : JwtAuthenticationEntryPoint
* author : crlee
* date : 2023/06/11
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/06/11 crlee
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
ResultVO resultVO = new ResultVO();
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
ObjectMapper mapper = new ObjectMapper();
//Convert object to JSON string
String jsonInString = mapper.writeValueAsString(resultVO);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON.toString());
response.setCharacterEncoding("UTF-8");
response.getWriter().println(jsonInString);
}
}

@ -0,0 +1,87 @@
package egovframework.com.jwt;
import egovframework.com.cmm.LoginVO;
import egovframework.let.utl.fcc.service.EgovStringUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
/**
* fileName : JwtAuthenticationFilter
* author : crlee
* date : 2023/06/11
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/06/11 crlee
*/
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private EgovJwtTokenUtil jwtTokenUtil;
public static final String HEADER_STRING = "Authorization";
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException {
boolean verificationFlag = true;
// step 1. request header에서 토큰을 가져온다.
String jwtToken = EgovStringUtil.isNullToString(req.getHeader(HEADER_STRING));
// step 2. 토큰에 내용이 있는지 확인해서 id값을 가져옴
// Exception 핸들링 추가처리 (토큰 유효성, 토큰 변조 여부, 토큰 만료여부)
// 내부적으로 parse하는 과정에서 해당 여부들이 검증됨
String id = null;
try {
id = jwtTokenUtil.getUserIdFromToken(jwtToken);
if (id == null) {
logger.debug("jwtToken not validate");
verificationFlag = false;
}
logger.debug("===>>> id = " + id);
} catch (IllegalArgumentException | ExpiredJwtException | MalformedJwtException | UnsupportedJwtException | SignatureException e) {
logger.debug("Unable to verify JWT Token: " + e.getMessage());
verificationFlag = false;
}
LoginVO loginVO = new LoginVO();
if( verificationFlag ){
logger.debug("jwtToken validated");
loginVO.setId(id);
loginVO.setUserSe( jwtTokenUtil.getUserSeFromToken(jwtToken) );
loginVO.setUniqId( jwtTokenUtil.getInfoFromToken("uniqId",jwtToken) );
loginVO.setOrgnztId( jwtTokenUtil.getInfoFromToken("orgnztId",jwtToken) );
loginVO.setName( jwtTokenUtil.getInfoFromToken("name",jwtToken) );
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginVO, null,
Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))
);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(req, res);
}
}

@ -1,57 +0,0 @@
package egovframework.com.jwt.config;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import egovframework.let.utl.fcc.service.EgovStringUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class JwtVerification {
@Autowired
private EgovJwtTokenUtil jwtTokenUtil;
public boolean isVerification(HttpServletRequest request) {
boolean verificationFlag = true;
// step 1. request header에서 토큰을 가져온다.
String jwtToken = EgovStringUtil.isNullToString(request.getHeader("authorization"));
// step 2. 토큰에 내용이 있는지 확인해서 username값을 가져옴
// Exception 핸들링 추가처리 (토큰 유효성, 토큰 변조 여부, 토큰 만료여부)
// 내부적으로 parse하는 과정에서 해당 여부들이 검증됨
String username = null;
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException | ExpiredJwtException | MalformedJwtException | UnsupportedJwtException | SignatureException e) {
log.debug("Unable to verify JWT Token: " + e.getMessage());
verificationFlag = false;
return verificationFlag;
}
log.debug("===>>> username = " + username);
// step 3. 가져온 username 유무 체크
if (username == null) {
log.debug("jwtToken not validate");
verificationFlag = false;
return verificationFlag;
}
log.debug("jwtToken validated");
return verificationFlag;
}
}

@ -0,0 +1,45 @@
package egovframework.com.security;
import egovframework.com.cmm.LoginVO;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* fileName : CustomAuthenticationPrincipalResolver
* author : crlee
* date : 2023/07/13
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/07/13 crlee
*/
public class CustomAuthenticationPrincipalResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(AuthenticationPrincipal.class) &&
parameter.getParameterType().equals(LoginVO.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null ||
authentication.getPrincipal() == null ||
"anonymousUser".equals(authentication.getPrincipal())
) {
return new LoginVO();
}
return authentication.getPrincipal();
}
}

@ -0,0 +1,100 @@
package egovframework.com.security;
import egovframework.com.jwt.JwtAuthenticationEntryPoint;
import egovframework.com.jwt.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
/**
* fileName : SecurityConfig
* author : crlee
* date : 2023/06/10
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/06/10 crlee
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
// 인증 예외 List
private String[] AUTH_WHITELIST = {
"/",
"/login/**",
"/uat/uia/actionLoginJWT.do",//JWT 로그인
"/uat/uia/actionLoginAPI.do",//일반 로그인
"/cmm/main/**.do", // 메인페이지
"/cmm/fms/FileDown.do", //파일 다운로드
"/cmm/fms/getImage.do", //갤러리 이미지보기
"/cop/smt/sim/egovIndvdlSchdulManageDailyListAPI.do", //일별 일정 조회
"/cop/smt/sim/egovIndvdlSchdulManageWeekListAPI.do", //주간 일정 조회
"/cop/smt/sim/egovIndvdlSchdulManageDetailAPI.do", //일정 상세조회
"/cop/bbs/selectUserBBSMasterInfAPI.do", //게시판 마스터 상세 조회
"/cop/bbs/selectBoardListAPI.do", //게시판 목록조회
"/cop/bbs/selectBoardArticleAPI.do", //게시물 상세조회
/* swagger v2 */
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/swagger-ui.html",
"/swagger-ui/**"
};
private static final String[] ORIGINS_WHITELIST = {
"http://localhost:3000",
};
@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("HEAD","POST","GET","DELETE","PUT"));
configuration.setAllowedOrigins(Arrays.asList(ORIGINS_WHITELIST));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize
.antMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated()
).sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.cors().and()
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(exceptionHandlingConfigurer ->
exceptionHandlingConfigurer
.authenticationEntryPoint(new JwtAuthenticationEntryPoint())
)
.build();
}
}

@ -0,0 +1,25 @@
package egovframework.com.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* fileName : WebMvcConfig
* author : crlee
* date : 2023/07/13
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/07/13 crlee
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new CustomAuthenticationPrincipalResolver());
}
}

@ -11,6 +11,9 @@ import org.egovframe.rte.fdl.cmmn.exception.EgovBizException;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@ -25,8 +28,6 @@ import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.jwt.config.JwtVerification;
import egovframework.let.cop.bbs.service.BoardMasterVO;
import egovframework.let.cop.bbs.service.EgovBBSAttributeManageService;
import io.swagger.v3.oas.annotations.Operation;
@ -55,10 +56,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
@RestController
@Tag(name="EgovBBSAttributeManageApiController",description = "게시판 속성관리")
public class EgovBBSAttributeManageApiController {
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
/** EgovBBSAttributeManageService */
@Resource(name = "EgovBBSAttributeManageService")
@ -104,11 +102,6 @@ public class EgovBBSAttributeManageApiController {
ResultVO resultVO = new ResultVO();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
boardMasterVO.setPageUnit(propertyService.getInt("Globals.pageUnit"));
boardMasterVO.setPageSize(propertyService.getInt("Globals.pageSize"));
@ -160,11 +153,6 @@ public class EgovBBSAttributeManageApiController {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
BoardMasterVO vo = bbsAttrbService.selectBBSMasterInf(searchVO);
resultMap.put("boardMasterVO", vo);
@ -197,20 +185,14 @@ public class EgovBBSAttributeManageApiController {
})
@PostMapping(value ="/cop/bbs/insertBBSMasterInfAPI.do")
public ResultVO insertBBSMasterInf(HttpServletRequest request,
BoardMasterVO boardMasterVO,
BindingResult bindingResult)
BoardMasterVO boardMasterVO,
BindingResult bindingResult,
@AuthenticationPrincipal LoginVO loginVO
)
throws Exception {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
beanValidator.validate(boardMasterVO, bindingResult);
if (bindingResult.hasErrors()) {
@ -235,18 +217,16 @@ public class EgovBBSAttributeManageApiController {
return resultVO;
}
if (isAuthenticated) {
boardMasterVO.setFrstRegisterId(user.getUniqId());
boardMasterVO.setUseAt("Y");
boardMasterVO.setTrgetId("SYSTEMDEFAULT_REGIST");
boardMasterVO.setPosblAtchFileSize(propertyService.getString("posblAtchFileSize"));
boardMasterVO.setFrstRegisterId(loginVO.getUniqId());
boardMasterVO.setUseAt("Y");
boardMasterVO.setTrgetId("SYSTEMDEFAULT_REGIST");
boardMasterVO.setPosblAtchFileSize(propertyService.getString("posblAtchFileSize"));
bbsAttrbService.insertBBSMastetInf(boardMasterVO);
bbsAttrbService.insertBBSMastetInf(boardMasterVO);
resultVO.setResult(resultMap);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
resultVO.setResult(resultMap);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
return resultVO;
}
@ -273,20 +253,14 @@ public class EgovBBSAttributeManageApiController {
})
@PutMapping(value ="/cop/bbs/updateBBSMasterInfAPI/{bbsId}.do")
public ResultVO updateBBSMasterInf(HttpServletRequest request,
@PathVariable("bbsId") String bbsId,
@RequestBody BoardMasterVO boardMasterVO,
BindingResult bindingResult) throws Exception {
@PathVariable("bbsId") String bbsId,
@RequestBody BoardMasterVO boardMasterVO,
BindingResult bindingResult,
@AuthenticationPrincipal LoginVO loginVO
) throws Exception {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
beanValidator.validate(boardMasterVO, bindingResult);
if (bindingResult.hasErrors()) {
@ -300,15 +274,13 @@ public class EgovBBSAttributeManageApiController {
return resultVO;
}
if (isAuthenticated) {
boardMasterVO.setLastUpdusrId(user.getUniqId());
boardMasterVO.setPosblAtchFileSize(propertyService.getString("posblAtchFileSize"));
bbsAttrbService.updateBBSMasterInf(boardMasterVO);
boardMasterVO.setLastUpdusrId(loginVO.getUniqId());
boardMasterVO.setPosblAtchFileSize(propertyService.getString("posblAtchFileSize"));
bbsAttrbService.updateBBSMasterInf(boardMasterVO);
resultVO.setResult(resultMap);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
resultVO.setResult(resultMap);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
return resultVO;
}
@ -333,47 +305,20 @@ public class EgovBBSAttributeManageApiController {
})
@PutMapping(value ="/cop/bbs/deleteBBSMasterInfAPI/{bbsId}.do")
public ResultVO deleteBBSMasterInf(HttpServletRequest request,
@AuthenticationPrincipal LoginVO loginVO,
@PathVariable("bbsId") String bbsId,
@RequestBody BoardMasterVO boardMasterVO) throws Exception {
ResultVO resultVO = new ResultVO();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
if (isAuthenticated) {
boardMasterVO.setLastUpdusrId(user.getUniqId());
boardMasterVO.setLastUpdusrId(loginVO.getUniqId());
bbsAttrbService.deleteBBSMasterInf(boardMasterVO);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
return resultVO;
}
private ResultVO handleAuthError(ResultVO resultVO) {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
return resultVO;
}
/**
* .( .)
*
* @throws EgovBizException
*/
protected boolean checkAuthority() throws Exception {
// 사용자권한 처리
if (!EgovUserDetailsHelper.isAuthenticated()) {
return false;
} else {
return true;
}
}
}

@ -13,6 +13,7 @@ import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@ -30,9 +31,7 @@ import egovframework.com.cmm.service.EgovFileMngService;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.com.cmm.service.FileVO;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.cmm.web.EgovFileDownloadController;
import egovframework.com.jwt.config.JwtVerification;
import egovframework.let.cop.bbs.service.BoardMasterVO;
import egovframework.let.cop.bbs.service.BoardVO;
import egovframework.let.cop.bbs.service.EgovBBSAttributeManageService;
@ -65,10 +64,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
@Tag(name="EgovBBSManageApiController",description = "게시물 관리")
public class EgovBBSManageApiController {
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
@Resource(name = "EgovBBSManageService")
private EgovBBSManageService bbsMngService;
@ -161,12 +156,10 @@ public class EgovBBSManageApiController {
@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
})
@PostMapping(value = "/cop/bbs/selectBoardListAPI.do", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResultVO selectBoardArticles(@RequestBody BoardVO boardVO)
public ResultVO selectBoardArticles(@RequestBody BoardVO boardVO, @AuthenticationPrincipal LoginVO user)
throws Exception {
ResultVO resultVO = new ResultVO();
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
BoardMasterVO vo = new BoardMasterVO();
vo.setBbsId(boardVO.getBbsId());
vo.setUniqId(user.getUniqId());
@ -216,16 +209,11 @@ public class EgovBBSManageApiController {
@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
})
@PostMapping(value = "/cop/bbs/selectBoardArticleAPI.do")
public ResultVO selectBoardArticle(@RequestBody BoardVO boardVO)
public ResultVO selectBoardArticle(@RequestBody BoardVO boardVO,@AuthenticationPrincipal LoginVO user)
throws Exception {
ResultVO resultVO = new ResultVO();
LoginVO user = new LoginVO();
if (EgovUserDetailsHelper.isAuthenticated()) {
user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
}
// 조회수 증가 여부 지정
boardVO.setPlusCount(true);
@ -322,33 +310,28 @@ public class EgovBBSManageApiController {
return resultVO;
}
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
} else if (jwtVerification.isVerification(request)) {
final Map<String, MultipartFile> files = multiRequest.getFileMap();
if (!files.isEmpty()) {
if ("".equals(atchFileId)) {
List<FileVO> result = fileUtil.parseFileInf(files, "BBS_", 0, atchFileId, "");
atchFileId = fileMngService.insertFileInfs(result);
boardVO.setAtchFileId(atchFileId);
} else {
FileVO fvo = new FileVO();
fvo.setAtchFileId(atchFileId);
int cnt = fileMngService.getMaxFileSN(fvo);
List<FileVO> _result = fileUtil.parseFileInf(files, "BBS_", cnt, atchFileId, "");
fileMngService.updateFileInfs(_result);
}
final Map<String, MultipartFile> files = multiRequest.getFileMap();
if (!files.isEmpty()) {
if ("".equals(atchFileId)) {
List<FileVO> result = fileUtil.parseFileInf(files, "BBS_", 0, atchFileId, "");
atchFileId = fileMngService.insertFileInfs(result);
boardVO.setAtchFileId(atchFileId);
} else {
FileVO fvo = new FileVO();
fvo.setAtchFileId(atchFileId);
int cnt = fileMngService.getMaxFileSN(fvo);
List<FileVO> _result = fileUtil.parseFileInf(files, "BBS_", cnt, atchFileId, "");
fileMngService.updateFileInfs(_result);
}
}
boardVO.setLastUpdusrId(user.getUniqId());
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setNttCn(unscript(boardVO.getNttCn())); // XSS 방지
boardVO.setLastUpdusrId(user.getUniqId());
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setNttCn(unscript(boardVO.getNttCn())); // XSS 방지
bbsMngService.updateBoardArticle(boardVO);
}
bbsMngService.updateBoardArticle(boardVO);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
@ -394,29 +377,25 @@ public class EgovBBSManageApiController {
return resultVO;
}
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
} else if (jwtVerification.isVerification(request)) {
List<FileVO> result = null;
String atchFileId = "";
final Map<String, MultipartFile> files = multiRequest.getFileMap();
if (!files.isEmpty()) {
result = fileUtil.parseFileInf(files, "BBS_", 0, "", "");
atchFileId = fileMngService.insertFileInfs(result);
}
boardVO.setAtchFileId(atchFileId);
boardVO.setFrstRegisterId(user.getUniqId());
boardVO.setBbsId(boardVO.getBbsId());
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
// board.setNttCn(unscript(board.getNttCn())); // XSS 방지
List<FileVO> result = null;
String atchFileId = "";
bbsMngService.insertBoardArticle(boardVO);
final Map<String, MultipartFile> files = multiRequest.getFileMap();
if (!files.isEmpty()) {
result = fileUtil.parseFileInf(files, "BBS_", 0, "", "");
atchFileId = fileMngService.insertFileInfs(result);
}
boardVO.setAtchFileId(atchFileId);
boardVO.setFrstRegisterId(user.getUniqId());
boardVO.setBbsId(boardVO.getBbsId());
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
// board.setNttCn(unscript(board.getNttCn())); // XSS 방지
bbsMngService.insertBoardArticle(boardVO);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
@ -462,33 +441,29 @@ public class EgovBBSManageApiController {
return resultVO;
}
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
} else if (jwtVerification.isVerification(request)) {
final Map<String, MultipartFile> files = multiRequest.getFileMap();
String atchFileId = "";
if (!files.isEmpty()) {
List<FileVO> result = fileUtil.parseFileInf(files, "BBS_", 0, "", "");
atchFileId = fileMngService.insertFileInfs(result);
}
final Map<String, MultipartFile> files = multiRequest.getFileMap();
String atchFileId = "";
boardVO.setAtchFileId(atchFileId);
boardVO.setReplyAt("Y");
boardVO.setFrstRegisterId(user.getUniqId());
boardVO.setBbsId(boardVO.getBbsId());
boardVO.setParnts(Long.toString(boardVO.getNttId()));
boardVO.setSortOrdr(boardVO.getSortOrdr());
boardVO.setReplyLc(Integer.toString(Integer.parseInt(boardVO.getReplyLc()) + 1));
if (!files.isEmpty()) {
List<FileVO> result = fileUtil.parseFileInf(files, "BBS_", 0, "", "");
atchFileId = fileMngService.insertFileInfs(result);
}
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setAtchFileId(atchFileId);
boardVO.setReplyAt("Y");
boardVO.setFrstRegisterId(user.getUniqId());
boardVO.setBbsId(boardVO.getBbsId());
boardVO.setParnts(Long.toString(boardVO.getNttId()));
boardVO.setSortOrdr(boardVO.getSortOrdr());
boardVO.setReplyLc(Integer.toString(Integer.parseInt(boardVO.getReplyLc()) + 1));
boardVO.setNttCn(unscript(boardVO.getNttCn())); // XSS 방지
boardVO.setNtcrNm(""); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
boardVO.setPassword(EgovFileScrty.encryptPassword("", user.getUniqId())); // dummy 오류 수정 (익명이 아닌 경우 validator 처리를 위해 dummy로 지정됨)
bbsMngService.insertBoardArticle(boardVO);
}
boardVO.setNttCn(unscript(boardVO.getNttCn())); // XSS 방지
bbsMngService.insertBoardArticle(boardVO);
//return "forward:/cop/bbs/selectBoardList.do";
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
@ -517,18 +492,12 @@ public class EgovBBSManageApiController {
@PutMapping(value = "/cop/bbs/deleteBoardArticleAPI/{nttId}.do")
public ResultVO deleteBoardArticle(@RequestBody BoardVO boardVO,
@PathVariable("nttId") String nttId,
@AuthenticationPrincipal LoginVO user,
HttpServletRequest request)
throws Exception {
ResultVO resultVO = new ResultVO();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
boardVO.setNttId(Long.parseLong(nttId));
boardVO.setLastUpdusrId(user.getUniqId());
@ -571,10 +540,6 @@ public class EgovBBSManageApiController {
return ret;
}
private ResultVO handleAuthError(ResultVO resultVO) {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
return resultVO;
}
}

@ -10,6 +10,7 @@ import org.egovframe.rte.fdl.cmmn.exception.EgovBizException;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@ -22,8 +23,6 @@ import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.jwt.config.JwtVerification;
import egovframework.let.cop.bbs.service.BoardMasterVO;
import egovframework.let.cop.bbs.service.EgovBBSAttributeManageService;
import egovframework.let.cop.com.service.BoardUseInfVO;
@ -54,9 +53,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
@Tag(name="EgovBBSUseInfoManageApiController",description = "게시판 이용정보 관리")
public class EgovBBSUseInfoManageApiController {
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
/** EgovBBSUseInfoManageService */
@Resource(name = "EgovBBSUseInfoManageService")
@ -102,10 +98,6 @@ public class EgovBBSUseInfoManageApiController {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
bdUseVO.setPageUnit(propertyService.getInt("Globals.pageUnit"));
bdUseVO.setPageSize(propertyService.getInt("Globals.pageSize"));
@ -191,10 +183,6 @@ public class EgovBBSUseInfoManageApiController {
BoardUseInfVO vo = bbsUseService.selectBBSUseInf(bdUseVO);// bbsItrgetId
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
// 시스템 사용 게시판의 경우 URL 표시
if ("SYSTEM_DEFAULT_BOARD".equals(vo.getTrgetId())) {
@ -238,20 +226,12 @@ public class EgovBBSUseInfoManageApiController {
@PostMapping(value ="/cop/com/insertBBSUseInfAPI.do")
public ResultVO insertBBSUseInf(HttpServletRequest request,
BoardUseInfVO bdUseVO,
BindingResult bindingResult
BindingResult bindingResult,
@AuthenticationPrincipal LoginVO loginVO
) throws Exception {
ResultVO resultVO = new ResultVO();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
beanValidator.validate(bdUseVO, bindingResult);
if (bindingResult.hasErrors()) {
@ -269,14 +249,12 @@ public class EgovBBSUseInfoManageApiController {
}
bdUseVO.setUseAt("Y");
bdUseVO.setFrstRegisterId(user.getUniqId());
bdUseVO.setFrstRegisterId(loginVO.getUniqId());
if (isAuthenticated) {
bbsUseService.insertBBSUseInf(bdUseVO);
bbsUseService.insertBBSUseInf(bdUseVO);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
return resultVO;
}
@ -303,46 +281,18 @@ public class EgovBBSUseInfoManageApiController {
@PutMapping(value ="/cop/com/updateBBSUseInfAPI/{bbsId}.do")
public ResultVO updateBBSUseInf(HttpServletRequest request,
@RequestBody BoardUseInfVO bdUseVO,
@PathVariable("bbsId") String bbsId) throws Exception {
@PathVariable("bbsId") String bbsId,
@AuthenticationPrincipal LoginVO loginVO
) throws Exception {
ResultVO resultVO = new ResultVO();
bdUseVO.setBbsId(bbsId);
bbsUseService.updateBBSUseInf(bdUseVO);
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
if (isAuthenticated) {
bdUseVO.setBbsId(bbsId);
bbsUseService.updateBBSUseInf(bdUseVO);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
return resultVO;
}
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
private ResultVO handleAuthError(ResultVO resultVO) {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
return resultVO;
}
/**
* .( .)
*
* @throws EgovBizException
*/
protected boolean checkAuthority() throws Exception {
// 사용자권한 처리
if (!EgovUserDetailsHelper.isAuthenticated()) {
return false;
} else {
return true;
}
}
}

@ -15,6 +15,7 @@ import org.egovframe.rte.fdl.cmmn.exception.EgovBizException;
import org.egovframe.rte.fdl.cryptography.EgovCryptoService;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -35,9 +36,7 @@ import egovframework.com.cmm.service.EgovFileMngService;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.com.cmm.service.FileVO;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.cmm.web.EgovFileDownloadController;
import egovframework.com.jwt.config.JwtVerification;
import egovframework.let.cop.smt.sim.service.EgovIndvdlSchdulManageService;
import egovframework.let.cop.smt.sim.service.IndvdlSchdulManageVO;
import io.swagger.v3.oas.annotations.Operation;
@ -66,10 +65,6 @@ public class EgovIndvdlSchdulManageApiController {
@Autowired
private DefaultBeanValidator beanValidator;
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
@ -113,17 +108,12 @@ public class EgovIndvdlSchdulManageApiController {
@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
})
@PostMapping(value = "/cop/smt/sim/egovIndvdlSchdulManageMonthListAPI.do")
public ResultVO EgovIndvdlSchdulManageMonthList(HttpServletRequest request,
@RequestBody Map<String, Object> commandMap) throws Exception {
public ResultVO EgovIndvdlSchdulManageMonthList(@AuthenticationPrincipal LoginVO loginVO, HttpServletRequest request,
@RequestBody Map<String, Object> commandMap) throws Exception {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
//일정구분 검색 유지
resultMap.put("searchKeyword",
commandMap.get("searchKeyword") == null ? "" : (String)commandMap.get("searchKeyword"));
@ -196,18 +186,12 @@ public class EgovIndvdlSchdulManageApiController {
HttpServletRequest request,
final MultipartHttpServletRequest multiRequest,
IndvdlSchdulManageVO indvdlSchdulManageVO,
BindingResult bindingResult
BindingResult bindingResult,
@AuthenticationPrincipal LoginVO loginVO
) throws Exception {
ResultVO resultVO = new ResultVO();
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
//서버 validate 체크
beanValidator.validate(indvdlSchdulManageVO, bindingResult);
if (bindingResult.hasErrors()) {
@ -232,8 +216,8 @@ public class EgovIndvdlSchdulManageApiController {
indvdlSchdulManageVO.setAtchFileId(_atchFileId); // 첨부파일 ID
//아이디 설정
indvdlSchdulManageVO.setFrstRegisterId(user.getUniqId());
indvdlSchdulManageVO.setLastUpdusrId(user.getUniqId());
indvdlSchdulManageVO.setFrstRegisterId(loginVO.getUniqId());
indvdlSchdulManageVO.setLastUpdusrId(loginVO.getUniqId());
indvdlSchdulManageVO.setSchdulDeptName("관리자부서");
indvdlSchdulManageVO.setSchdulDeptId("ORGNZT_0000000000000");
@ -264,17 +248,13 @@ public class EgovIndvdlSchdulManageApiController {
})
@PostMapping(value = "/cop/smt/sim/egovIndvdlSchdulManageDetailAPI.do")
public ResultVO EgovIndvdlSchdulManageDetail(
@RequestBody Map<String, Object> commandMap)
@RequestBody Map<String, Object> commandMap,
@AuthenticationPrincipal LoginVO user)
throws Exception {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
LoginVO user = new LoginVO();
if (EgovUserDetailsHelper.isAuthenticated()) {
user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
}
IndvdlSchdulManageVO indvdlSchdulManageVO = new IndvdlSchdulManageVO();
indvdlSchdulManageVO.setSchdulId((String)commandMap.get("schdulId"));
@ -353,15 +333,12 @@ public class EgovIndvdlSchdulManageApiController {
IndvdlSchdulManageVO indvdlSchdulManageVO = new IndvdlSchdulManageVO();
indvdlSchdulManageVO.setSchdulId(schdulId);
// 기존 세션 체크 인증에서 토큰 방식으로 변경
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
} else {
egovIndvdlSchdulManageService.deleteIndvdlSchdulManage(indvdlSchdulManageVO);//schdulId
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
egovIndvdlSchdulManageService.deleteIndvdlSchdulManage(indvdlSchdulManageVO);//schdulId
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
return resultVO;
}
@ -388,18 +365,13 @@ public class EgovIndvdlSchdulManageApiController {
public ResultVO IndvdlSchdulManageModifyActor(
final MultipartHttpServletRequest multiRequest,
IndvdlSchdulManageVO indvdlSchdulManageVO,
BindingResult bindingResult)
BindingResult bindingResult,
@AuthenticationPrincipal LoginVO user)
throws Exception {
ResultVO resultVO = new ResultVO();
Map<String, Object> resultMap = new HashMap<String, Object>();
if (!EgovUserDetailsHelper.isAuthenticated()) {
return handleAuthError(resultVO); // server-side 권한 확인
}
//로그인 객체 선언
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
//서버 validate 체크
beanValidator.validate(indvdlSchdulManageVO, bindingResult);
@ -685,26 +657,4 @@ public class EgovIndvdlSchdulManageApiController {
return sOutput;
}
/**
* .( .)
*
* @param model
* @throws EgovBizException
*/
protected boolean checkAuthority(ModelMap model) throws Exception {
// 사용자권한 처리
if (!EgovUserDetailsHelper.isAuthenticated()) {
model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
return false;
} else {
return true;
}
}
private ResultVO handleAuthError(ResultVO resultVO) {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
return resultVO;
}
}

@ -6,7 +6,7 @@ import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@ -14,8 +14,6 @@ import org.springframework.web.bind.annotation.RestController;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import egovframework.com.jwt.config.JwtVerification;
import egovframework.let.uat.esm.service.EgovSiteManagerService;
import egovframework.let.utl.sim.service.EgovFileScrty;
import io.swagger.v3.oas.annotations.Operation;
@ -49,14 +47,7 @@ public class EgovSiteManagerApiController {
@Resource(name = "siteManagerService")
private EgovSiteManagerService siteManagerService;
/** JwtVerification */
@Autowired
private JwtVerification jwtVerification;
private ResultVO handleAuthError(ResultVO resultVO) {
resultVO.setResultCode(ResponseCode.AUTH_ERROR.getCode());
resultVO.setResultMessage(ResponseCode.AUTH_ERROR.getMessage());
return resultVO;
}
/**
* .
* @param map: String old_password, new_password
@ -76,13 +67,9 @@ public class EgovSiteManagerApiController {
@PostMapping(value = "/uat/esm/jwtAuthAPI.do")
public ResultVO jwtAuthentication(HttpServletRequest request) throws Exception {
ResultVO resultVO = new ResultVO();
// Headers에서 Authorization 속성값에 발급한 토큰값이 정상인지 확인
if (!jwtVerification.isVerification(request)) {
resultVO = handleAuthError(resultVO); // 토큰 확인
}else{
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
}
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
return resultVO;
}
/**
@ -103,13 +90,9 @@ public class EgovSiteManagerApiController {
@ApiResponse(responseCode = "800", description = "저장시 내부 오류")
})
@PostMapping(value = "/uat/esm/updateAdminPasswordAPI.do")
public ResultVO updateAdminPassword(@RequestBody Map<String,String> param, HttpServletRequest request) throws Exception {
public ResultVO updateAdminPassword(@RequestBody Map<String,String> param, HttpServletRequest request, @AuthenticationPrincipal LoginVO user) throws Exception {
ResultVO resultVO = new ResultVO();
// Headers에서 Authorization 속성값에 발급한 토큰값이 정상인지 확인
if (!jwtVerification.isVerification(request)) {
return handleAuthError(resultVO); // 토큰 확인
}
LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
String old_password = param.get("old_password");
String new_password = param.get("new_password");
String login_id = user.getId();

@ -4,7 +4,9 @@ import java.util.HashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import egovframework.com.cmm.util.EgovUserDetailsHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
@ -13,19 +15,18 @@ import org.egovframe.rte.fdl.cmmn.trace.LeaveaTrace;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.LoginVO;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.jwt.config.EgovJwtTokenUtil;
import egovframework.com.jwt.EgovJwtTokenUtil;
import egovframework.let.uat.uia.service.EgovLoginService;
import lombok.extern.slf4j.Slf4j;
@ -133,9 +134,9 @@ public class EgovLoginApiController {
log.debug("===>>> loginVO.getId() = "+loginVO.getId());
log.debug("===>>> loginVO.getPassword() = "+loginVO.getPassword());
String jwtToken = jwtTokenUtil.generateToken(loginVO);
String jwtToken = jwtTokenUtil.generateToken(loginResultVO);
String username = jwtTokenUtil.getUsernameFromToken(jwtToken);
String username = jwtTokenUtil.getUserSeFromToken(jwtToken);
log.debug("Dec jwtToken username = "+username);
//서버사이드 권한 체크 통과를 위해 삽입
@ -170,10 +171,11 @@ public class EgovLoginApiController {
@ApiResponse(responseCode = "200", description = "로그아웃 성공"),
})
@GetMapping(value = "/uat/uia/actionLogoutAPI.do")
public ResultVO actionLogoutJSON(HttpServletRequest request) throws Exception {
public ResultVO actionLogoutJSON(HttpServletRequest request, HttpServletResponse response) throws Exception {
ResultVO resultVO = new ResultVO();
RequestContextHolder.currentRequestAttributes().removeAttribute("LoginVO", RequestAttributes.SCOPE_SESSION);
new SecurityContextLogoutHandler().logout(request, response, null);
resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

@ -0,0 +1,101 @@
package egovframework.let.uat.uia.web;
import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.*;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* fileName : EgovLoginApiContollerTest
* author : crlee
* date : 2023/06/19
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2023/06/19 crlee
*/
@TestInstance(TestInstance. Lifecycle.PER_CLASS)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EgovLoginApiControllerTest {
@Value("${server.servlet.context-path}")
String CONTEXT_PATH;
String URL = "http://localhost";
@LocalServerPort
int randomServerPort;
String SERVER_URL;
@BeforeAll
void init(){
this.SERVER_URL = String.format("%s:%s%s", URL,randomServerPort,CONTEXT_PATH);
}
@Test
@DisplayName("인증 성공")
void hasToken(){
String token = getToken();
ResponseEntity<ResultVO> result = callApi(token);
Assertions.assertThat( result.getStatusCode() ).isEqualTo( HttpStatus.OK );
Assertions.assertThat( result.getBody().getResultCode() ).isEqualTo( ResponseCode.SUCCESS.getCode() );
Assertions.assertThat( result.getBody().getResultMessage() ).isEqualTo( ResponseCode.SUCCESS.getMessage() );
}
@Test
@DisplayName("인증 실패 - Token null")
void noToken(){
ResponseEntity<ResultVO> result = callApi(null);
Assertions.assertThat( result.getStatusCode() ).isEqualTo( HttpStatus.UNAUTHORIZED );
Assertions.assertThat( result.getBody().getResultCode() ).isEqualTo( ResponseCode.AUTH_ERROR.getCode() );
Assertions.assertThat( result.getBody().getResultMessage() ).isEqualTo( ResponseCode.AUTH_ERROR.getMessage() );
}
@Test
@DisplayName("인증 실패 - Wrong Token")
void wrongToken(){
ResponseEntity<ResultVO> result = callApi("123123123123123T&*#$SDF123");
Assertions.assertThat( result.getStatusCode() ).isEqualTo( HttpStatus.UNAUTHORIZED );
Assertions.assertThat( result.getBody().getResultCode() ).isEqualTo( ResponseCode.AUTH_ERROR.getCode() );
Assertions.assertThat( result.getBody().getResultMessage() ).isEqualTo( ResponseCode.AUTH_ERROR.getMessage() );
}
String getToken(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String,Object> params = new HashMap<>();
params.put("id","admin");
params.put("password","1");
params.put("userSe","USR");
HttpEntity request = new HttpEntity(params,headers);
TestRestTemplate rest = new TestRestTemplate();
ResponseEntity<HashMap> res = rest.exchange(this.SERVER_URL + "/uat/uia/actionLoginJWT.do", HttpMethod.POST,request , HashMap.class);
assertThat( res.getStatusCode() ).isEqualTo( HttpStatus.OK );
HashMap<String,Object> body = (HashMap<String,Object>) res.getBody();
assertThat( body.get("jToken") ).isNotNull();
assertThat( body.get("resultCode") ).isEqualTo("200");
assertThat( body.get("resultMessage") ).isEqualTo("성공 !!!");
String token = body.get("jToken").toString();
return token;
}
ResponseEntity<ResultVO> callApi(String token){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", token);
HttpEntity request = new HttpEntity(headers);
TestRestTemplate rest = new TestRestTemplate();
return rest.exchange(this.SERVER_URL + "/uat/esm/jwtAuthAPI.do", HttpMethod.POST, request,ResultVO.class);
}
}
Loading…
Cancel
Save