Skip to content

Commit

Permalink
jwt 토큰 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
HeeSung98 committed Nov 27, 2023
1 parent 28c494f commit ee53221
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.weather.user.security.handler.LoginFailureHandler;
import com.weather.user.security.handler.LoginSuccessHandler;
import com.weather.user.security.service.AuthUserDetailsService;
import com.weather.user.util.JWTUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand Down Expand Up @@ -48,7 +49,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{

@Bean
public LoginSuccessHandler loginSuccessHandler() {
return new LoginSuccessHandler(passwordEncoder());
return new LoginSuccessHandler(jwtUtil());
}

@Bean
Expand All @@ -75,4 +76,9 @@ public ApiLoginFilter apiLoginFilter(AuthenticationManager authenticationManager

return apiLoginFilter;
}

@Bean
public JWTUtil jwtUtil() {
return new JWTUtil();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.weather.user.security.filter;

import com.weather.user.security.handler.LoginSuccessHandler;
import com.weather.user.util.JWTUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand All @@ -16,6 +17,7 @@

@Log4j2
public class ApiLoginFilter extends AbstractAuthenticationProcessingFilter {

public ApiLoginFilter(String defaultFilterProcessUrl) {
super(defaultFilterProcessUrl);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,25 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weather.user.security.dto.AuthUserDTO;
import com.weather.user.util.JWTUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import net.minidev.json.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

@Log4j2
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private ObjectMapper objectMapper = new ObjectMapper();
private PasswordEncoder passwordEncoder;
private JWTUtil jwtUtil;

public LoginSuccessHandler(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
public LoginSuccessHandler(JWTUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}

@Override
Expand All @@ -35,13 +32,17 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
log.info(authentication);

AuthUserDTO authUserDTO = (AuthUserDTO) authentication.getPrincipal();
boolean fromSocial = authUserDTO.isFromSocial();
String name = authUserDTO.getName();

log.info(authUserDTO);

String result = objectMapper.writeValueAsString(authUserDTO);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(result);
try {
String token = jwtUtil.generateToken(authUserDTO.getEmail());

String result = objectMapper.writeValueAsString(authUserDTO);
result = result.replace("}", ", \"token\": \"" + token + "\"}");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
23 changes: 23 additions & 0 deletions user/src/main/java/com/weather/user/util/JWTUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
import io.jsonwebtoken.impl.DefaultJws;
import lombok.extern.log4j.Log4j2;

import java.time.ZonedDateTime;
Expand All @@ -21,4 +23,25 @@ public String generateToken(String text) throws Exception{
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes("UTF-8"))
.compact();
}

public String validateAndExtract(String stringToken) throws Exception {
String value = null;

try {
DefaultJws defaultJws = (DefaultJws) Jwts.parser()
.setSigningKey(secretKey.getBytes("UTF-8"))
.parseClaimsJws(stringToken);

log.info(defaultJws);
log.info(defaultJws.getBody().getClass());

DefaultClaims claims = (DefaultClaims) defaultJws.getBody();

value = claims.getSubject();
} catch (Exception e) {
e.printStackTrace();
}

return value;
}
}
32 changes: 32 additions & 0 deletions user/src/test/java/com/weather/user/security/JWTTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.weather.user.security;

import com.weather.user.util.JWTUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class JWTTest {
private JWTUtil jwtUtil;

@BeforeEach
public void testBefore() {
System.out.println("testBefore.................");
jwtUtil = new JWTUtil();
}

@Test
public void testEncode() throws Exception {
String email = "[email protected]";

String str = jwtUtil.generateToken(email);

System.out.println(str);

Thread.sleep(5000);

String resultEmail = jwtUtil.validateAndExtract(str);

System.out.println(resultEmail);
}
}
12 changes: 0 additions & 12 deletions user/src/test/java/com/weather/user/service/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,4 @@ void signupTest() {

userService.signup(userDTO);
}

@Test
void signinTest() {
UserDTO userDTO = UserDTO.builder()
.email("[email protected]")
.password("1234")
.fromSocial(true)
.build();

Optional<UserDTO> result = userService.signin(userDTO.getEmail(), userDTO.getPassword(), userDTO.isFromSocial());
System.out.println("result: " + result);
}
}

0 comments on commit ee53221

Please sign in to comment.