로그인 작업중.

cks
강석 최 2023-11-24 18:01:02 +09:00
parent 8738a08189
commit 701047e22e
6 changed files with 81 additions and 77 deletions

View File

@ -13,9 +13,7 @@ function App() {
return ( return (
<div className="wrap"> <div className="wrap">
<React.StrictMode>
<RootRoutes /> <RootRoutes />
</React.StrictMode>
</div> </div>
) )
} }

View File

@ -74,6 +74,7 @@ function EgovLoginContent(props) {
EgovNet.requestFetch(loginUrl, EgovNet.requestFetch(loginUrl,
requestOptions, requestOptions,
(resp) => { (resp) => {
debugger
let resultVO = resp.resultVO; let resultVO = resp.resultVO;
let jToken = resp?.jToken || null; let jToken = resp?.jToken || null;
@ -107,7 +108,7 @@ function EgovLoginContent(props) {
<p className="txt">전자정부표준프레임워크 경량환경 홈페이지 로그인 페이지입니다.<br />로그인을 하시면 모든 서비스를 제한없이 이용하실 있습니다.</p> <p className="txt">전자정부표준프레임워크 경량환경 홈페이지 로그인 페이지입니다.<br />로그인을 하시면 모든 서비스를 제한없이 이용하실 있습니다.</p>
<div className="login_box"> <div className="login_box">
<form name="" method="" action="" > <form name="" method="" action="" onSubmit={submitFormHandler}>
<fieldset> <fieldset>
<legend>로그인</legend> <legend>로그인</legend>
<span className="group"> <span className="group">
@ -126,7 +127,7 @@ function EgovLoginContent(props) {
<Link to={URL.JOIN}><em>회원가입</em></Link> <Link to={URL.JOIN}><em>회원가입</em></Link>
</Col> </Col>
</Row> </Row>
<button type="button" onClick={submitFormHandler}><span>LOGIN</span></button> <button type="submit"><span>LOGIN</span></button>
</fieldset> </fieldset>
</form> </form>
</div> </div>

View File

@ -252,8 +252,8 @@ function CodeViewer(props) {
} }
CodeViewer.defaultProps = { CodeViewer.defaultProps = {
docCode: 'KDS 10 10 00', docCode: 'KDS 24 10 11',
docName: '설계기준 총칙' docName: '교량 설계 일반사항(한계상태설계법)'
} }
export default CodeViewer; export default CodeViewer;

View File

@ -101,4 +101,9 @@ public class EgovLoginApiController extends BaseController {
} }
return resultMap; return resultMap;
} }
@RequestMapping("/auth/loginSuccess")
public HashMap<String, Object> loginSuccess(HttpServletRequest request, HttpServletResponse response){
return new HashMap<>();
}
} }

View File

@ -3,20 +3,22 @@ package com.dbnt.kcscbackend.config.jwt;
import com.dbnt.kcscbackend.auth.entity.UserInfo; import com.dbnt.kcscbackend.auth.entity.UserInfo;
import com.dbnt.kcscbackend.config.egov.EgovProperties; import com.dbnt.kcscbackend.config.egov.EgovProperties;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.Serializable; import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* *
* @author : * @author :
* @since : 2023. 8. 9. * @since : 2023. 8. 9.
* @version : 1.0 * @version : 1.0
@ -40,59 +42,65 @@ import java.util.Map;
@Component @Component
public class EgovJwtTokenUtil implements Serializable{ public class EgovJwtTokenUtil implements Serializable{
private static final long serialVersionUID = -5180902194184255251L; private static final long serialVersionUID = -5180902194184255251L;
//public static final long JWT_TOKEN_VALIDITY = 24 * 60 * 60; //하루 //public static final long JWT_TOKEN_VALIDITY = 24 * 60 * 60; //하루
public static final long JWT_TOKEN_VALIDITY = (long) ((1 * 60 * 60) / 60) * 60; //토큰의 유효시간 설정, 기본 60분 public static final long JWT_TOKEN_VALIDITY = (long) ((1 * 60 * 60) / 60) * 60; //토큰의 유효시간 설정, 기본 60분
public static final String SECRET_KEY = EgovProperties.getProperty("Globals.jwt.secret");
//retrieve username from jwt token
public String getUserIdFromToken(String token) {
Claims claims = getClaimFromToken(token);
return claims.get("id").toString();
}
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 Claims getClaimFromToken(String token) {
final Claims claims = getAllClaimsFromToken(token);
return claims;
}
//for retrieveing any information from token we will need the secret key
public Claims getAllClaimsFromToken(String token) {
log.debug("===>>> secret = "+SECRET_KEY);
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
//generate token for user public static final String SECRET_KEY = EgovProperties.getProperty("Globals.jwt.secret");
public String generateToken(UserInfo loginVO) {
return doGenerateToken(loginVO, "Authorization");
}
//while creating the token - //retrieve username from jwt token
//1. Define claims of the token, like Issuer, Expiration, Subject, and the ID public String getUserIdFromToken(String token) {
//2. Sign the JWT using the HS512 algorithm and secret key. Claims claims = getClaimFromToken(token);
//3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1) return claims.get("id").toString();
// compaction of the JWT to a URL-safe string }
private String doGenerateToken(UserInfo loginVO, String subject) { 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 Claims getClaimFromToken(String token) {
final Claims claims = getAllClaimsFromToken(token);
return claims;
}
Map<String, Object> claims = new HashMap<>(); //for retrieveing any information from token we will need the secret key
claims.put("id", loginVO.getUserId() ); public Claims getAllClaimsFromToken(String token) {
claims.put("userSe", loginVO.getUserSe() ); log.debug("===>>> secret = "+SECRET_KEY);
claims.put("uniqId", loginVO.getUserSeq() );
claims.put("type", subject);
log.debug("===>>> secret = "+SECRET_KEY); return Jwts.parserBuilder().setSigningKey(SECRET_KEY.getBytes(StandardCharsets.UTF_8)).build().parseClaimsJws(token).getBody();
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(); //generate token for user
} public String generateToken(UserInfo loginVO) {
return doGenerateToken(loginVO);
}
//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(UserInfo loginVO) {
Map<String, Object> claims = new HashMap<>();
claims.put("id", loginVO.getUserId() );
claims.put("userSe", loginVO.getUserSe() );
claims.put("uniqId", loginVO.getUserSeq() );
claims.put("type", "Authorization");
log.debug("===>>> secret = "+SECRET_KEY);
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setSubject("Authorization")
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
.signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS512);
return builder.compact();
}
} }

View File

@ -71,8 +71,6 @@ public class SecurityConfig {
"/", "/",
"/login/**", "/login/**",
"/login", "/login",
"/auth/login-jwt",//JWT 로그인
"/auth/login",//일반 로그인
"/auth/join",//회원가입 "/auth/join",//회원가입
"/cmm/main/**.do", // 메인페이지 "/cmm/main/**.do", // 메인페이지
"/cmm/fms/FileDown.do", //파일 다운로드 "/cmm/fms/FileDown.do", //파일 다운로드
@ -118,15 +116,17 @@ public class SecurityConfig {
} }
@Bean @Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize http.httpBasic().disable()
.csrf().disable()
.formLogin().disable();
http.authorizeHttpRequests(authorize -> authorize
.antMatchers(AUTH_WHITELIST).permitAll() .antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers(HttpMethod.GET,AUTH_GET_WHITELIST).permitAll() .antMatchers(HttpMethod.GET,AUTH_GET_WHITELIST).permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
); );
http.sessionManagement((sessionManagement) -> http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class) http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(exceptionHandlingConfigurer -> .exceptionHandling(exceptionHandlingConfigurer ->
@ -134,14 +134,6 @@ public class SecurityConfig {
.authenticationEntryPoint(new JwtAuthenticationEntryPoint()) .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
); );
http.httpBasic().disable()
.csrf().disable()
.formLogin().disable();
// http.authorizeHttpRequests()
// .requestMatchers(new AntPathRequestMatcher("/auth/login")).permitAll()
// .anyRequest().authenticated();
http.cors().and().addFilterBefore(jsonUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); http.cors().and().addFilterBefore(jsonUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build(); return http.build();
} }
@ -150,11 +142,11 @@ public class SecurityConfig {
public AuthenticationSuccessHandler loginSuccessHandler() { public AuthenticationSuccessHandler loginSuccessHandler() {
return (request, response, authentication) -> { return (request, response, authentication) -> {
UserInfo info = (UserInfo)authentication.getPrincipal(); UserInfo info = (UserInfo)authentication.getPrincipal();
if (info != null && info.getUserId() != null && !info.getUserId().equals("")){
String jwtToken = jwtTokenUtil.generateToken(info); String jwtToken = jwtTokenUtil.generateToken(info);
String userName = jwtTokenUtil.getUserSeFromToken(jwtToken); // String userName = jwtTokenUtil.getUserSeFromToken(jwtToken);
} response.addHeader("Authorization", "BEARER "+jwtToken);
new DefaultRedirectStrategy().sendRedirect(request,response,"/");
}; };
} }