用户登录

pull/1/head
陈沅 2 years ago
parent 2c6291536b
commit e614ecd4ce

@ -110,6 +110,11 @@
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
</dependencies>
<build>

@ -23,6 +23,7 @@ public class TokenProvider {
* @return jwt
*/
public static JwtUser getJWTUser(String jwtToken) {
jwtToken = jwtToken.replace("Bearer ", "");
try {
Claims claims = Jwts.parser()
.setSigningKey(

@ -1,5 +1,6 @@
package com.sztzjy.forex.trading_trading.controller;
import com.sztzjy.forex.trading_trading.annotation.AnonymousAccess;
import com.sztzjy.forex.trading_trading.dto.PageVO;
import com.sztzjy.forex.trading_trading.entity.Log;
import com.sztzjy.forex.trading_trading.service.LogService;
@ -24,6 +25,7 @@ public class LogController {
@ApiOperation("根据条件查询操作日志(分页)")
@GetMapping("findAll")
@AnonymousAccess
public ResultEntity<PageVO<Log>> findAll(@ApiParam("ip地址") @RequestParam(required = false) String ipAddress,
@ApiParam("开始时间") @RequestParam(required = false) Long startTime,
@ApiParam("结束时间") @RequestParam(required = false) Long endTime,

@ -13,6 +13,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
@ -22,20 +23,27 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("api/sysUser")
@RequiredArgsConstructor
public class UserController {
private AuthenticationManagerBuilder authenticationManagerBuilder;
@Resource
private AuthenticationManager authenticationManager;
@AnonymousAccess
@OperateLog(description = "用户登录")
@ApiOperation(value = "用户登录",httpMethod = "POST")
@ApiOperation(value = "用户登录", httpMethod = "POST")
@PostMapping("login")
public ResultEntity<LoginResult> login(@ApiParam("用户名")@RequestParam String username,
@ApiParam("加密后的密文")@RequestParam String passwordEncode){
public ResultEntity<LoginResult> login(@ApiParam("用户名") @RequestParam String username,
@ApiParam("加密后的密文") @RequestParam String passwordEncode) {
String password;
try {
@ -43,14 +51,42 @@ public class UserController {
} catch (Exception e) {
throw new IllegalArgumentException("密码错误");
}
JwtUser jwtUser = TzApi.foreignExchangeTradingLogin(username, password);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
String md5Pwd = calculateMD5(password);
String hashPwd = formatHash(md5Pwd);
JwtUser jwtUser = TzApi.foreignExchangeTradingLogin(username, hashPwd);
Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenProvider.createToken(jwtUser);
return new ResultEntity<LoginResult>(LoginResult.create(jwtUser,token));
return new ResultEntity<LoginResult>(LoginResult.create(jwtUser, token));
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static String formatHash(String hash) {
StringBuilder formattedHash = new StringBuilder();
for (int i = 0; i < hash.length(); i += 2) {
formattedHash.append(hash.substring(i, i + 2));
if (i < hash.length() - 2) {
formattedHash.append("-");
}
}
return formattedHash.toString();
}
}

@ -1,17 +1,28 @@
package com.sztzjy.forex.trading_trading.util;
import cn.hutool.json.JSONObject;
import com.nimbusds.jose.shaded.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class HttpUtils {
public static String CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
// 发送GET请求
public static String sendGet(String url) throws IOException {
HttpURLConnection connection = null;
@ -41,41 +52,46 @@ public class HttpUtils {
}
// 发送POST请求
public static String sendPost(String url, String requestBody) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
public static JSONObject sendPost(String url, String paramStr, String contentType, String token) throws IOException {
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
int statusCode = connection.getResponseCode();
if(statusCode != HttpURLConnection.HTTP_OK){
log.error("请求失败,返回码:" + statusCode + ",返回消息:" + connection.getResponseMessage());
return null;
}
connection.setDoOutput(true);
JSONObject ret = new JSONObject();
HttpPost method = new HttpPost(url);
StringEntity entity = new StringEntity(paramStr, "utf-8");
entity.setContentEncoding("UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
if (StringUtils.isEmpty(contentType))
entity.setContentType("application/json");
else
entity.setContentType(contentType);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
if (StringUtils.isNotEmpty(token)) {
method.setHeader("Authorization", "Bearer " + token);
}
} finally {
if (reader != null) {
reader.close();
method.setEntity(entity);
int timeout = 60000;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.build();
method.setConfig(requestConfig);
HttpClient client = HttpClients.createDefault();
HttpResponse resp = client.execute(method);
int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
return null;
}
if (connection != null) {
connection.disconnect();
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
ret.set("statusCode",statusCode);
if(StringUtils.isNotEmpty(respString)){
ret.set("respString",respString);
}
return ret;
}catch (Exception e) {
e.printStackTrace();
log.info("接口请求失败,失败原因:"+e.getMessage());
}
return response.toString();
return null;
}
}

@ -23,15 +23,15 @@ public class RsaUtil {
// System.out.println("公钥:" + keyPair.getPublicKey());
// System.out.println("私钥:" + keyPair.getPrivateKey());
//System.out.println("\n");
String text1 = encryptByPublicKey("@123");
String text1 = encryptByPublicKey("123qwe");
// String text1 = encryptByPrivateKey("123");
System.out.println(text1);
//String text1 = "Bs+MJo8yrGxvwD/G5QGTihU6lh/PjaDKQNxBDs66GQrNXoX0ttzX0grYFxWh8MibHkHikkw8rLsoxXk6bQOzs0eHst/yzj823sTZRDBYdx0oYoEKeda7s7xjYheq4nBnHJn8HVkQbYtchddRRfKVcwyBrUQquhlnzmnfZQ98QiU=";
// String text1 = "CP7GpqY3Tw3DSazqwMHvlRys0/RARfjNL0fgw5IEXEHdZB2K+7G8Ro+wVAm9fiViMba3KcQidG5g244RrpD0HJc/g6PVW4kn81xx1WHjW0SgVUUrsjj4RgHUnUyY/lN0506Ng945svGrGd6pXb+XdtETv4ZKau5EHdR6L/TOR8I=";
// String text1 = "dWRzqk2DC/rm55B+m1Is4mwTnPoc3qoDIZ41Plie6s4vsJwDdHzoWhnIx1pfdFAwEZ3eQ6FV7tcfHJwHDFzNal15e1c2+EFThmWdqdgGNCXttH/c/fsmzaXda5kQRzQxqbhvF96KmJKtshzq23766iLV1Vm3KUsvB6c7bP5yKYc=";
//String text2 = decryptByPrivateKey(text1);
String text2 = decryptByPrivateKey("R/t6KFVPbCgYSVlYJ4ULuFFwn29/RlLo/IBeXqdtwm0ulIcG0iTDqbCNcQZChE8iN/AL7S4MoGL/HWZArEqAz4BdDmYgLggykX/hhu1fue7tpefyVEnW5TF27rFBCxo1cH0kB1VP0FbwlWHDqG1GCnHOBZbS6j4yUTqu41WBmq4=");
System.out.println(text2);
// String text2 = decryptByPrivateKey("R/t6KFVPbCgYSVlYJ4ULuFFwn29/RlLo/IBeXqdtwm0ulIcG0iTDqbCNcQZChE8iN/AL7S4MoGL/HWZArEqAz4BdDmYgLggykX/hhu1fue7tpefyVEnW5TF27rFBCxo1cH0kB1VP0FbwlWHDqG1GCnHOBZbS6j4yUTqu41WBmq4=");
// System.out.println(text2);
}
public static String encryptByPublicKey(String text) throws Exception {

@ -1,32 +1,52 @@
package com.sztzjy.forex.trading_trading.util;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.shaded.gson.JsonObject;
import com.sztzjy.forex.trading_trading.config.security.JwtUser;
import java.net.URLEncoder;
public class TzApi {
private final static String API_URL = "http://Cloud.sztzjy.com";
private final static String LOGIN_URL = API_URL + "/api/foreignExchangeTradingLogin";
private final static String LOGIN_URL = API_URL + "/Account/FireignExchangeTradingLogin";
public static JwtUser foreignExchangeTradingLogin(String userName, String password) {
try {
String requestBody = "userName=" + userName + "&password=" + password;
String result = HttpUtils.sendPost(LOGIN_URL, requestBody);
if (result == null) {
String requestBody = "username=" + URLEncoder.encode(userName, "UTF8") +
"&password=" + URLEncoder.encode(password, "UTF8");
JSONObject object = HttpUtils.sendPost(
LOGIN_URL,
requestBody,
HttpUtils.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED,
null);
if (object == null) {
throw new IllegalArgumentException("登录失败");
}
JSONObject object = JSONUtil.parseObj(result);
JSONObject jsonObject = object.getJSONObject("respString");
JSONObject resultObject = jsonObject.getJSONObject("result");
int code = resultObject.getInt("code");
if(code!= HttpStatus.HTTP_OK){
throw new IllegalArgumentException("登录失败");
}
JSONObject dataObject = resultObject.getJSONObject("data");
JwtUser user = new JwtUser();
user.setUserId(object.getStr("userId"));
user.setName(object.getStr("name"));
user.setRoleId(object.getInt("roleId"));
user.setSchoolId(object.getInt("schoolId"));
user.setClassId(object.getInt("classId"));
user.setUserId(dataObject.getStr("userId"));
user.setName(dataObject.getStr("name"));
user.setRoleId(dataObject.getInt("roleId"));
user.setSchoolId(dataObject.getInt("schoolId"));
user.setClassId(dataObject.getInt("classId"));
user.setUsername(userName);
user.setPassword(password);
return user;
} catch (Exception e) {
e.printStackTrace();

Loading…
Cancel
Save