Skip to content
This repository was archived by the owner on Apr 18, 2024. It is now read-only.
1 change: 1 addition & 0 deletions backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ exclude(module: 'protobuf-java')
compile group: 'cn.cisdigital', name: 'exception-component', version:'1.0.0'
compile group: 'com.dianping.cat', name: 'cat-client', version:'3.0.0'
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version:'6.0.9.Final'
compile group: 'io.jsonwebtoken', name: 'jjwt', version:'0.6.0'
compile group: 'org.aspectj', name: 'aspectjweaver', version:'1.9.6'
testCompile(group: 'org.springframework.boot', name: 'spring-boot-starter-test', version:'2.3.3.RELEASE') {
exclude(module: 'junit-vintage-engine')
Expand Down
12 changes: 7 additions & 5 deletions backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@
</dependency>


<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
Expand All @@ -71,11 +77,7 @@
<version>3.34.0</version>
</dependency>

<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>


<dependency>
<groupId>org.projectlombok</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@

import org.apache.iotdb.admin.common.exception.BaseException;
import org.apache.iotdb.admin.common.exception.ErrorCode;
import org.apache.iotdb.admin.tool.JJwtTool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;

import javax.servlet.http.HttpServletRequest;

Expand All @@ -35,15 +35,20 @@ public static void userAuthentication(Integer userId, HttpServletRequest request
if (userId == null) {
throw new BaseException(ErrorCode.NO_USER, ErrorCode.NO_USER_MSG);
}
DecodedJWT authorization = JWT.decode(request.getHeader("Authorization"));
Integer tokenUserId = authorization.getClaim("userId").asInt();
String authorization = request.getHeader("Authorization");
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
if (null == claimsByToken) {
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
}
Integer tokenUserId = claimsByToken.get("userId", Integer.class);
if (!tokenUserId.equals(userId)) {
throw new BaseException(ErrorCode.USER_AUTH_FAIL, ErrorCode.USER_AUTH_FAIL_MSG);
}
}

public static Integer getUserId(HttpServletRequest request) {
DecodedJWT authentication = JWT.decode(request.getHeader("Authorization"));
return authentication.getClaim("userId").asInt();
String authorization = request.getHeader("Authorization");
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
return claimsByToken.get("userId", Integer.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public void addInterceptors(InterceptorRegistry registry) {
List<String> paths = new ArrayList();
paths.add("/servers/**");
paths.add("/get");
paths.add("/save");
paths.add("/delete");
paths.add("/downloadFile/**");
interceptorRegistration.addPathPatterns(paths);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@
import org.apache.iotdb.admin.model.vo.ConnectionVO;
import org.apache.iotdb.admin.service.ConnectionService;
import org.apache.iotdb.admin.service.UserService;
import org.apache.iotdb.admin.tool.JJwtTool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
Expand All @@ -42,8 +41,6 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.InetAddress;
import java.util.Calendar;
import java.util.List;

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

Expand All @@ -94,11 +91,11 @@ public BaseVO delete(@RequestParam("userId") Integer userId, HttpServletRequest
@ApiOperation("Get information of user")
public BaseVO<User> getUser(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
DecodedJWT decode = JWT.decode(authorization);
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
User user = new User();
if (decode != null) {
Integer userId = decode.getClaim("userId").asInt();
String name = decode.getClaim("name").asString();
if (claimsByToken != null) {
Integer userId = claimsByToken.get("userId", Integer.class);
String name = claimsByToken.get("name", String.class);
user.setId(userId);
user.setName(name);
}
Expand All @@ -121,22 +118,4 @@ public String welcome() {
+ "</html>";
return str;
}

private String getToken(User user) throws BaseException {
Calendar instance = Calendar.getInstance();
try {
instance.add(Calendar.HOUR, 24);
String token =
JWT.create()
.withClaim("userId", user.getId())
.withClaim("name", user.getName())
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
logger.info(user.getName() + "login successfully");
return token;
} catch (Exception e) {
logger.info(e.getMessage());
throw new BaseException(ErrorCode.GET_TOKEN_FAIL, ErrorCode.GET_TOKEN_FAIL_MSG);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,29 @@

import org.apache.iotdb.admin.common.exception.BaseException;
import org.apache.iotdb.admin.common.exception.ErrorCode;
import org.apache.iotdb.admin.tool.JJwtTool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import io.jsonwebtoken.Claims;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TokenFilter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws BaseException {
JWTVerifier jwtVerifier;
try {
jwtVerifier =
JWT.require(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()))
.build();
} catch (UnknownHostException e) {
e.printStackTrace();
throw new BaseException(ErrorCode.SET_JWT_FAIL, ErrorCode.SET_JWT_FAIL_MSG);
String authorization = request.getHeader("Authorization");
if (null == authorization || "".equals(authorization)) {
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
}
Claims claimsByToken = JJwtTool.getClaimsByToken(authorization);
if (ObjectUtils.isEmpty(claimsByToken)) {
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
}
try {
String authorization = request.getHeader("Authorization");
jwtVerifier.verify(authorization);
} catch (Exception e) {
e.printStackTrace();
Integer userId = claimsByToken.get("userId", Integer.class);
if (null == userId) {
throw new BaseException(ErrorCode.TOKEN_ERR, ErrorCode.TOKEN_ERR_MSG);
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

@Autowired private UserMapper userMapper;
Expand Down
68 changes: 68 additions & 0 deletions backend/src/main/java/org/apache/iotdb/admin/tool/JJwtTool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.admin.tool;

import org.apache.iotdb.admin.model.entity.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/** date:2022/12/6 author:yzf project_name:backend */
@Slf4j
public class JJwtTool {
private static String secret =
"HSyJ0eXAiOiJKV1QasdfffffffSd3g8923402347523fffasdfasgwaegwaegawegawegawegawetwgewagagew"
+ "asdf23r23DEEasdfawef134t2fawt2g325gafasdfasdfiLCJhbGciOiJIUzI1NiJ9";

public static String generateToken(User user) {
log.info("user=" + user.toString());
Date now = new Date();
// Calendar instance = Calendar.getInstance();
// instance.add(Calendar.HOUR_OF_DAY, 24);
Date expireDate = new Date(new Date().getTime() + (1000 * 60 * 60 * 10));
return Jwts.builder()
.setHeaderParam("type", "JWT")
.setSubject(user.getId() + "")
.setIssuedAt(now) // 签发时间
.claim("userId", user.getId())
.claim("name", user.getName())
.setExpiration(expireDate) // 过期时间
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}

/** 解析token */
public static Claims getClaimsByToken(String token) {
try {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
} catch (Exception e) {
System.out.println("validate is token error");
return null;
}
}

/** 判断 token 是否过期 */
public boolean isTokenExpired(Date expiration) {
return expiration.before(new Date());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@

package org.apache.iotdb.admin.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.iotdb.admin.model.entity.User;
import org.apache.iotdb.admin.tool.JJwtTool;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -33,9 +34,6 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import java.net.InetAddress;
import java.util.Calendar;

@SpringBootTest
class ConnectionControllerTest {
private MockMvc mvc;
Expand Down Expand Up @@ -100,16 +98,11 @@ void getAllConnections() throws Exception {
}

private String getToken() {
Calendar instance = Calendar.getInstance();
try {
instance.add(Calendar.HOUR, 24);
String token =
JWT.create()
.withClaim("userId", 1)
.withClaim("name", "root")
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
return token;
User user = new User();
user.setId(1);
user.setName("root");
return JJwtTool.generateToken(user);
} catch (Exception e) {
e.printStackTrace();
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@

package org.apache.iotdb.admin.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.iotdb.admin.model.entity.User;
import org.apache.iotdb.admin.tool.JJwtTool;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
Expand All @@ -34,9 +35,6 @@
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.net.InetAddress;
import java.util.Calendar;

@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class IotDBControllerTest {
Expand All @@ -46,16 +44,11 @@ class IotDBControllerTest {
private String token = getToken();

private String getToken() {
Calendar instance = Calendar.getInstance();
try {
instance.add(Calendar.HOUR, 24);
String token =
JWT.create()
.withClaim("userId", 1)
.withClaim("name", "root")
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("IOTDB:" + InetAddress.getLocalHost().getHostAddress()));
return token;
User user = new User();
user.setId(1);
user.setName("root");
return JJwtTool.generateToken(user);
} catch (Exception e) {
e.printStackTrace();
return null;
Expand Down
Loading