From cbf066b1130e2f13f347a57a73a46f37443ccac3 Mon Sep 17 00:00:00 2001 From: heshunme Date: Mon, 1 Jul 2024 01:55:25 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Jwt=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=92=8CSpring=20Security=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 23 +++++++++-- .../org/cmh/backend/Config/CorsConfig.java | 26 ------------- .../cmh/backend/Config/SecurityConfig.java | 23 +++++++++++ .../java/org/cmh/backend/Utils/JwtUtil.java | 39 +++++++++++++++++++ 4 files changed, 81 insertions(+), 30 deletions(-) delete mode 100644 src/main/java/org/cmh/backend/Config/CorsConfig.java create mode 100644 src/main/java/org/cmh/backend/Config/SecurityConfig.java create mode 100644 src/main/java/org/cmh/backend/Utils/JwtUtil.java diff --git a/pom.xml b/pom.xml index 428b562..39cc9bb 100644 --- a/pom.xml +++ b/pom.xml @@ -50,10 +50,25 @@ org.springframework.boot spring-boot-starter-data-jpa - - - - + + org.springframework.boot + spring-boot-starter-security + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + org.springframework.boot spring-boot-starter-web diff --git a/src/main/java/org/cmh/backend/Config/CorsConfig.java b/src/main/java/org/cmh/backend/Config/CorsConfig.java deleted file mode 100644 index 7852636..0000000 --- a/src/main/java/org/cmh/backend/Config/CorsConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.cmh.backend.Config; -// CorsConfig.java - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class CorsConfig { - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins("http://localhost:8080") - .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") - .allowedHeaders("*") - .allowCredentials(true); - } - }; - } -} - diff --git a/src/main/java/org/cmh/backend/Config/SecurityConfig.java b/src/main/java/org/cmh/backend/Config/SecurityConfig.java new file mode 100644 index 0000000..c917d0a --- /dev/null +++ b/src/main/java/org/cmh/backend/Config/SecurityConfig.java @@ -0,0 +1,23 @@ +package org.cmh.backend.Config; + +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.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +public class SecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + // Use the new API to disable CSRF + http.csrf(AbstractHttpConfigurer::disable) + // Permit all requests + .authorizeHttpRequests(authorize -> authorize + .anyRequest().permitAll() + ); + + return http.build(); + } +} diff --git a/src/main/java/org/cmh/backend/Utils/JwtUtil.java b/src/main/java/org/cmh/backend/Utils/JwtUtil.java new file mode 100644 index 0000000..97b1c69 --- /dev/null +++ b/src/main/java/org/cmh/backend/Utils/JwtUtil.java @@ -0,0 +1,39 @@ +package org.cmh.backend.Utils; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; + +import javax.crypto.SecretKey; +import java.util.Date; + +public class JwtUtil { + + private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor("9cbf491e853995ab73a2a3dcd7206549".getBytes()); + + public static String generateToken(String username) { + return Jwts.builder() + .setSubject(username) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours + .signWith(SECRET_KEY, SignatureAlgorithm.HS256) + .compact(); + } + + public static Claims extractClaims(String token) { + return Jwts.parserBuilder() + .setSigningKey(SECRET_KEY) + .build() + .parseClaimsJws(token) + .getBody(); + } + + public static boolean isTokenValid(String token, String username) { + return username.equals(extractClaims(token).getSubject()) && !isTokenExpired(token); + } + + private static boolean isTokenExpired(String token) { + return extractClaims(token).getExpiration().before(new Date()); + } +} From 1f99db9523456c4d736e2b5d1a8c3308c528e17a Mon Sep 17 00:00:00 2001 From: heshunme Date: Mon, 1 Jul 2024 16:46:18 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9JwtUtil=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E7=A1=AE=E4=BF=9D?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=8F=AF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/cmh/backend/Utils/JwtUtilTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/test/java/org/cmh/backend/Utils/JwtUtilTest.java diff --git a/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java new file mode 100644 index 0000000..78dcdb8 --- /dev/null +++ b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java @@ -0,0 +1,47 @@ +package org.cmh.backend.Utils; + +import io.jsonwebtoken.Claims; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Date; + +public class JwtUtilTest { + + @Test + public void testGenerateToken() throws InterruptedException { + String username = "testUser"; + String token = JwtUtil.generateToken(username); + Thread.sleep(100); + + // Validate token is not empty + Assert.assertNotNull("Token should not be null", token); + Assert.assertFalse("Token should not be empty", token.isEmpty()); + + // Parse the token to check claims + Claims claims = JwtUtil.extractClaims(token); +// System.out.println(claims.getIssuedAt().toString()); + + + // Validate claims + Assert.assertTrue("Token shoud be valid", JwtUtil.isTokenValid(token, username)); + Assert.assertEquals("Username in claims should match", username, claims.getSubject()); + Assert.assertTrue("Token should be issued in the past", new Date().after(claims.getIssuedAt())); + Assert.assertTrue("Token expiration should be in the future", new Date().before(claims.getExpiration())); + } + + @Test + public void testTokenExpiration() { + String username = "testUser"; + String token = JwtUtil.generateToken(username); + + Claims claims = JwtUtil.extractClaims(token); + + long expirationTime = claims.getExpiration().getTime(); + long currentTime = new Date().getTime(); + + // Validate token expires within 10 hours + Assert.assertTrue("Token should expire within 10 hours", expirationTime - currentTime <= 1000 * 60 * 60 * 10); + } +} + From df25c9c13c4a72f09005743dfed83780220bd00a Mon Sep 17 00:00:00 2001 From: heshunme Date: Mon, 1 Jul 2024 16:46:18 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=AF=B9JwtUtil=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E7=A1=AE=E4=BF=9D?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=8F=AF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/org/cmh/backend/Utils/JwtUtilTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java index 78dcdb8..6722473 100644 --- a/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java +++ b/src/test/java/org/cmh/backend/Utils/JwtUtilTest.java @@ -24,7 +24,7 @@ public class JwtUtilTest { // Validate claims - Assert.assertTrue("Token shoud be valid", JwtUtil.isTokenValid(token, username)); + Assert.assertTrue("Token should be valid", JwtUtil.isTokenValid(token, username)); Assert.assertEquals("Username in claims should match", username, claims.getSubject()); Assert.assertTrue("Token should be issued in the past", new Date().after(claims.getIssuedAt())); Assert.assertTrue("Token expiration should be in the future", new Date().before(claims.getExpiration()));