Skip to content
This repository was archived by the owner on Apr 18, 2024. It is now read-only.

Commit 23862b4

Browse files
authored
Safe Token (#34)
1 parent ea0774b commit 23862b4

12 files changed

Lines changed: 138 additions & 114 deletions

File tree

backend/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ exclude(module: 'protobuf-java')
5858
compile group: 'cn.cisdigital', name: 'exception-component', version:'1.0.0'
5959
compile group: 'com.dianping.cat', name: 'cat-client', version:'3.0.0'
6060
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version:'6.0.9.Final'
61+
compile group: 'io.jsonwebtoken', name: 'jjwt', version:'0.6.0'
6162
compile group: 'org.aspectj', name: 'aspectjweaver', version:'1.9.6'
6263
testCompile(group: 'org.springframework.boot', name: 'spring-boot-starter-test', version:'2.3.3.RELEASE') {
6364
exclude(module: 'junit-vintage-engine')

backend/pom.xml

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@
5454
</dependency>
5555

5656

57+
<dependency>
58+
<groupId>io.jsonwebtoken</groupId>
59+
<artifactId>jjwt</artifactId>
60+
<version>0.6.0</version>
61+
</dependency>
62+
5763
<dependency>
5864
<groupId>org.springframework.boot</groupId>
5965
<artifactId>spring-boot-starter-log4j2</artifactId>
@@ -71,11 +77,7 @@
7177
<version>3.34.0</version>
7278
</dependency>
7379

74-
<dependency>
75-
<groupId>com.auth0</groupId>
76-
<artifactId>java-jwt</artifactId>
77-
<version>3.4.0</version>
78-
</dependency>
80+
7981

8082
<dependency>
8183
<groupId>org.projectlombok</groupId>

backend/src/main/java/org/apache/iotdb/admin/common/utils/AuthenticationUtils.java

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@
2121

2222
import org.apache.iotdb.admin.common.exception.BaseException;
2323
import org.apache.iotdb.admin.common.exception.ErrorCode;
24+
import org.apache.iotdb.admin.tool.JJwtTool;
2425

25-
import com.auth0.jwt.JWT;
26-
import com.auth0.jwt.interfaces.DecodedJWT;
26+
import io.jsonwebtoken.Claims;
2727

2828
import javax.servlet.http.HttpServletRequest;
2929

@@ -35,15 +35,20 @@ public static void userAuthentication(Integer userId, HttpServletRequest request
3535
if (userId == null) {
3636
throw new BaseException(ErrorCode.NO_USER, ErrorCode.NO_USER_MSG);
3737
}
38-
DecodedJWT authorization = JWT.decode(request.getHeader("Authorization"));
39-
Integer tokenUserId = authorization.getClaim("userId").asInt();
38+
String authorization = request.getHeader("Authorization");
39+
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
40+
if (null == claimsByToken) {
41+
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
42+
}
43+
Integer tokenUserId = claimsByToken.get("userId", Integer.class);
4044
if (!tokenUserId.equals(userId)) {
4145
throw new BaseException(ErrorCode.USER_AUTH_FAIL, ErrorCode.USER_AUTH_FAIL_MSG);
4246
}
4347
}
4448

4549
public static Integer getUserId(HttpServletRequest request) {
46-
DecodedJWT authentication = JWT.decode(request.getHeader("Authorization"));
47-
return authentication.getClaim("userId").asInt();
50+
String authorization = request.getHeader("Authorization");
51+
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
52+
return claimsByToken.get("userId", Integer.class);
4853
}
4954
}

backend/src/main/java/org/apache/iotdb/admin/config/FilterConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ public void addInterceptors(InterceptorRegistry registry) {
3939
List<String> paths = new ArrayList();
4040
paths.add("/servers/**");
4141
paths.add("/get");
42+
paths.add("/save");
43+
paths.add("/delete");
4244
paths.add("/downloadFile/**");
4345
interceptorRegistration.addPathPatterns(paths);
4446
}

backend/src/main/java/org/apache/iotdb/admin/controller/UserController.java

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,9 @@
2828
import org.apache.iotdb.admin.model.vo.ConnectionVO;
2929
import org.apache.iotdb.admin.service.ConnectionService;
3030
import org.apache.iotdb.admin.service.UserService;
31+
import org.apache.iotdb.admin.tool.JJwtTool;
3132

32-
import com.auth0.jwt.JWT;
33-
import com.auth0.jwt.algorithms.Algorithm;
34-
import com.auth0.jwt.interfaces.DecodedJWT;
33+
import io.jsonwebtoken.Claims;
3534
import io.swagger.annotations.Api;
3635
import io.swagger.annotations.ApiOperation;
3736
import org.slf4j.Logger;
@@ -42,8 +41,6 @@
4241
import javax.servlet.http.HttpServletRequest;
4342
import javax.servlet.http.HttpServletResponse;
4443

45-
import java.net.InetAddress;
46-
import java.util.Calendar;
4744
import java.util.List;
4845

4946
@RestController
@@ -70,7 +67,7 @@ public BaseVO<ConnectionVO> login(
7067
int userId = user.getId();
7168
List<ConnVO> connVOs = connectionService.getAllConnections(userId);
7269
ConnectionVO connectionVO = new ConnectionVO(connVOs, userId, name);
73-
response.addHeader("Authorization", getToken(user));
70+
response.addHeader("Authorization", JJwtTool.generateToken(user));
7471
return BaseVO.success("Login successful", connectionVO);
7572
}
7673

@@ -94,11 +91,11 @@ public BaseVO delete(@RequestParam("userId") Integer userId, HttpServletRequest
9491
@ApiOperation("Get information of user")
9592
public BaseVO<User> getUser(HttpServletRequest request) {
9693
String authorization = request.getHeader("Authorization");
97-
DecodedJWT decode = JWT.decode(authorization);
94+
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
9895
User user = new User();
99-
if (decode != null) {
100-
Integer userId = decode.getClaim("userId").asInt();
101-
String name = decode.getClaim("name").asString();
96+
if (claimsByToken != null) {
97+
Integer userId = claimsByToken.get("userId", Integer.class);
98+
String name = claimsByToken.get("name", String.class);
10299
user.setId(userId);
103100
user.setName(name);
104101
}
@@ -121,22 +118,4 @@ public String welcome() {
121118
+ "</html>";
122119
return str;
123120
}
124-
125-
private String getToken(User user) throws BaseException {
126-
Calendar instance = Calendar.getInstance();
127-
try {
128-
instance.add(Calendar.HOUR, 24);
129-
String token =
130-
JWT.create()
131-
.withClaim("userId", user.getId())
132-
.withClaim("name", user.getName())
133-
.withExpiresAt(instance.getTime())
134-
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
135-
logger.info(user.getName() + "login successfully");
136-
return token;
137-
} catch (Exception e) {
138-
logger.info(e.getMessage());
139-
throw new BaseException(ErrorCode.GET_TOKEN_FAIL, ErrorCode.GET_TOKEN_FAIL_MSG);
140-
}
141-
}
142121
}

backend/src/main/java/org/apache/iotdb/admin/filter/TokenFilter.java

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,36 +21,29 @@
2121

2222
import org.apache.iotdb.admin.common.exception.BaseException;
2323
import org.apache.iotdb.admin.common.exception.ErrorCode;
24+
import org.apache.iotdb.admin.tool.JJwtTool;
2425

25-
import com.auth0.jwt.JWT;
26-
import com.auth0.jwt.JWTVerifier;
27-
import com.auth0.jwt.algorithms.Algorithm;
26+
import io.jsonwebtoken.Claims;
27+
import org.springframework.util.ObjectUtils;
2828
import org.springframework.web.servlet.HandlerInterceptor;
2929

3030
import javax.servlet.http.HttpServletRequest;
3131
import javax.servlet.http.HttpServletResponse;
3232

33-
import java.net.InetAddress;
34-
import java.net.UnknownHostException;
35-
3633
public class TokenFilter implements HandlerInterceptor {
3734
@Override
3835
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
3936
throws BaseException {
40-
JWTVerifier jwtVerifier;
41-
try {
42-
jwtVerifier =
43-
JWT.require(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()))
44-
.build();
45-
} catch (UnknownHostException e) {
46-
e.printStackTrace();
47-
throw new BaseException(ErrorCode.SET_JWT_FAIL, ErrorCode.SET_JWT_FAIL_MSG);
37+
String authorization = request.getHeader("Authorization");
38+
if (null == authorization || "".equals(authorization)) {
39+
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
40+
}
41+
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
42+
if (ObjectUtils.isEmpty(claimsByToken)) {
43+
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
4844
}
49-
try {
50-
String authorization = request.getHeader("Authorization");
51-
jwtVerifier.verify(authorization);
52-
} catch (Exception e) {
53-
e.printStackTrace();
45+
Integer userId = claimsByToken.get("userId", Integer.class);
46+
if (null == userId) {
5447
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
5548
}
5649
return true;

backend/src/main/java/org/apache/iotdb/admin/service/impl/UserServiceImpl.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@
2727

2828
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
2929
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
30+
import lombok.extern.slf4j.Slf4j;
3031
import org.springframework.beans.factory.annotation.Autowired;
3132
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
3233
import org.springframework.stereotype.Service;
3334

3435
@Service
36+
@Slf4j
3537
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
3638

3739
@Autowired private UserMapper userMapper;
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.iotdb.admin.tool;
20+
21+
import org.apache.iotdb.admin.model.entity.User;
22+
23+
import io.jsonwebtoken.Claims;
24+
import io.jsonwebtoken.Jwts;
25+
import io.jsonwebtoken.SignatureAlgorithm;
26+
import lombok.extern.slf4j.Slf4j;
27+
28+
import java.util.Date;
29+
30+
/** date:2022/12/6 author:yzf project_name:backend */
31+
@Slf4j
32+
public class JJwtTool {
33+
private static String secret =
34+
"HSyJ0eXAiOiJKV1QasdfffffffSd3g8923402347523fffasdfasgwaegwaegawegawegawegawetwgewagagew"
35+
+ "asdf23r23DEEasdfawef134t2fawt2g325gafasdfasdfiLCJhbGciOiJIUzI1NiJ9";
36+
37+
public static String generateToken(User user) {
38+
log.info("user=" + user.toString());
39+
Date now = new Date();
40+
// Calendar instance = Calendar.getInstance();
41+
// instance.add(Calendar.HOUR_OF_DAY, 24);
42+
Date expireDate = new Date(new Date().getTime() + (1000 * 60 * 60 * 10));
43+
return Jwts.builder()
44+
.setHeaderParam("type", "JWT")
45+
.setSubject(user.getId() + "")
46+
.setIssuedAt(now) // 签发时间
47+
.claim("userId", user.getId())
48+
.claim("name", user.getName())
49+
.setExpiration(expireDate) // 过期时间
50+
.signWith(SignatureAlgorithm.HS512, secret)
51+
.compact();
52+
}
53+
54+
/** 解析token */
55+
public static Claims getClaimsByToken(String token) {
56+
try {
57+
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
58+
} catch (Exception e) {
59+
System.out.println("validate is token error");
60+
return null;
61+
}
62+
}
63+
64+
/** 判断 token 是否过期 */
65+
public boolean isTokenExpired(Date expiration) {
66+
return expiration.before(new Date());
67+
}
68+
}

backend/src/test/java/org/apache/iotdb/admin/controller/ConnectionControllerTest.java

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@
1919

2020
package org.apache.iotdb.admin.controller;
2121

22-
import com.auth0.jwt.JWT;
23-
import com.auth0.jwt.algorithms.Algorithm;
22+
import org.apache.iotdb.admin.model.entity.User;
23+
import org.apache.iotdb.admin.tool.JJwtTool;
24+
2425
import org.junit.jupiter.api.Test;
2526
import org.springframework.beans.factory.annotation.Autowired;
2627
import org.springframework.boot.test.context.SpringBootTest;
@@ -33,9 +34,6 @@
3334
import org.springframework.transaction.annotation.Transactional;
3435
import org.springframework.web.context.WebApplicationContext;
3536

36-
import java.net.InetAddress;
37-
import java.util.Calendar;
38-
3937
@SpringBootTest
4038
class ConnectionControllerTest {
4139
private MockMvc mvc;
@@ -100,16 +98,11 @@ void getAllConnections() throws Exception {
10098
}
10199

102100
private String getToken() {
103-
Calendar instance = Calendar.getInstance();
104101
try {
105-
instance.add(Calendar.HOUR, 24);
106-
String token =
107-
JWT.create()
108-
.withClaim("userId", 1)
109-
.withClaim("name", "root")
110-
.withExpiresAt(instance.getTime())
111-
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
112-
return token;
102+
User user = new User();
103+
user.setId(1);
104+
user.setName("root");
105+
return JJwtTool.generateToken(user);
113106
} catch (Exception e) {
114107
e.printStackTrace();
115108
return null;

backend/src/test/java/org/apache/iotdb/admin/controller/IotDBControllerTest.java

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@
1919

2020
package org.apache.iotdb.admin.controller;
2121

22-
import com.auth0.jwt.JWT;
23-
import com.auth0.jwt.algorithms.Algorithm;
22+
import org.apache.iotdb.admin.model.entity.User;
23+
import org.apache.iotdb.admin.tool.JJwtTool;
24+
2425
import org.junit.jupiter.api.MethodOrderer;
2526
import org.junit.jupiter.api.Order;
2627
import org.junit.jupiter.api.Test;
@@ -34,9 +35,6 @@
3435
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
3536
import org.springframework.web.context.WebApplicationContext;
3637

37-
import java.net.InetAddress;
38-
import java.util.Calendar;
39-
4038
@SpringBootTest
4139
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
4240
class IotDBControllerTest {
@@ -46,16 +44,11 @@ class IotDBControllerTest {
4644
private String token = getToken();
4745

4846
private String getToken() {
49-
Calendar instance = Calendar.getInstance();
5047
try {
51-
instance.add(Calendar.HOUR, 24);
52-
String token =
53-
JWT.create()
54-
.withClaim("userId", 1)
55-
.withClaim("name", "root")
56-
.withExpiresAt(instance.getTime())
57-
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
58-
return token;
48+
User user = new User();
49+
user.setId(1);
50+
user.setName("root");
51+
return JJwtTool.generateToken(user);
5952
} catch (Exception e) {
6053
e.printStackTrace();
6154
return null;

0 commit comments

Comments
 (0)