用户登录

pull/1/head
陈沅
parent 09fc9c1df4
commit ad439b459e

@ -18,6 +18,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<jjwt.version>0.10.8</jjwt.version>
</properties>
<dependencies>
<dependency>
@ -91,11 +92,24 @@
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-core</artifactId>-->
<!-- <version>5.6.14.Final</version>-->
<!-- </dependency>-->
<!-- 添加jwt依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>

@ -55,7 +55,8 @@ public class OperateLogAspect implements Ordered {
Log logRecord = new Log();
JwtUser curUser = null;
try {
curUser = TokenProvider.getJWTUser(request);
String token = request.getHeader("token");
curUser = TokenProvider.getJWTUser(token);
} catch (Exception e) {
logRecord.setOperatorName("匿名");
}

@ -52,7 +52,7 @@ public class AuthenticationFilter extends OncePerRequestFilter {
if (!StringUtils.startsWithIgnoreCase(token, "Bearer ")) {
throw new UnAuthorizedException("令牌错误: 缺失Bearer..");
}
JwtUser currentUser = tokenProvider.getClaims(token);
JwtUser currentUser = TokenProvider.getJWTUser(token);
Authentication authentication = new UsernamePasswordAuthenticationToken(currentUser, "****", currentUser.getAuthorities());
request.getUserPrincipal();
SecurityContextHolder.getContext().setAuthentication(authentication);

@ -0,0 +1,52 @@
package com.sztzjy.forex.trading_trading.config.security;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
*
*
* @author
*/
@ApiModel("用户登录结果集")
@Setter
@Getter
public class LoginResult {
@ApiModelProperty("用户ID")
private String userId;
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("访问令牌")
private String accessToken;
@ApiModelProperty("角色Id")
private int roleId;
@ApiModelProperty("用户所在班级id")
private int classId;
@ApiModelProperty("用户所在学校id")
private int schoolId;
/**
*
*
* @param jwtUser
* @param accessToken
* @return LoginResult
*/
public static LoginResult create(JwtUser jwtUser, String accessToken) {
LoginResult result = new LoginResult();
result.setUserId(jwtUser.getUserId());
result.setRoleId(jwtUser.getRoleId());
result.setName(jwtUser.getName());
result.setAccessToken(accessToken);
result.setClassId(jwtUser.getClassId());
result.setSchoolId(jwtUser.getSchoolId());
return result;
}
}

@ -1,54 +1,70 @@
package com.sztzjy.forex.trading_trading.config.security;
import com.google.common.collect.Lists;
import com.sztzjy.forex.trading_trading.config.Constant;
import com.sztzjy.forex.trading_trading.config.exception.UnAuthorizedException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.security.Key;
import java.util.Date;
@Component
public class TokenProvider {
private final static String SECRET = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAghgsx+OLLThi7c+/HgCaRla8n+/QLHt++uscoK22dMeaVa3WJvRb5C5qtHGzj9V74pI96JpxdWWCN3Zr1QtanQIDAQABAkB2fWRUD1jVMBVS+rPctLnPNPMKTRdzXGv0SC5D3tRfGZqdcfsmZg8hzBVndHxngmwZS73d+hPjofcdefDDnXq1AiEAz/r1AMF7fweN70mbKgBJuTja37puJMsH2Szwrvb5jlcCIQCgIaLZ5d9J7OomL0NwH8ghba/xgBEpKzErfGbFnTfeKwIgc8ptczFFV1DWZb2eJIEqinOr79l0jwl2YiQSD+cyw1sCIHqxCvv1Wx5jPgy/zeYNE+Q5DMP3Ii7u/x+Yk436JiI9AiEAio84hFm44YTUuV7YCYsbyvnCn/vtcAaqZlczbeHlP1I=";
private final static long EXP_TIME = 1000 * 60 * 60 * 2;
/**
* jwtToken
*
* @param jwtToken jwtToken
* @return jwt
*/
public static JwtUser getClaims(String jwtToken) {
//todo 解析用户token
return null;
}
public static JwtUser getJWTUser(HttpServletRequest request) {
if (!(request.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken)) {
throw new UnAuthorizedException("身份认证失败");
}
String jwtToken = request.getHeader(Constant.AUTHORIZATION);
if (StringUtils.hasText(jwtToken)) {
return getJWTUser(jwtToken);
}
throw new UnAuthorizedException("身份认证失败");
}
public static JwtUser getJWTUser(String tokenValue) {
public static JwtUser getJWTUser(String jwtToken) {
try {
JwtUser principal = getClaims(tokenValue);
return principal;
Claims claims = Jwts.parser()
.setSigningKey(
new SecretKeySpec(
SECRET.getBytes("UTF-8"),
SignatureAlgorithm.HS512.getJcaName()
)
)
.parseClaimsJws(jwtToken)
.getBody();
JwtUser jwtUser = new JwtUser();
jwtUser.setName(claims.get("name").toString());
jwtUser.setUserId(claims.get("userId").toString());
jwtUser.setRoleId(Integer.valueOf(claims.get("roleId").toString()));
jwtUser.setClassId(Integer.valueOf(claims.get("classId").toString()));
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId").toString()));
jwtUser.setUsername(claims.get("name").toString());
return jwtUser;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String createToken(JwtUser jwtUser) {
Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
return Jwts.builder()
.claim("userId", jwtUser.getUserId())
.claim("roleId", jwtUser.getRoleId())
.claim("name", jwtUser.getName())
.claim("classId", jwtUser.getClassId())
.claim("schoolId", jwtUser.getSchoolId())
.claim("username", jwtUser.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expiration)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
}

@ -0,0 +1,56 @@
package com.sztzjy.forex.trading_trading.controller;
import com.sztzjy.forex.trading_trading.annotation.AnonymousAccess;
import com.sztzjy.forex.trading_trading.annotation.OperateLog;
import com.sztzjy.forex.trading_trading.config.security.JwtUser;
import com.sztzjy.forex.trading_trading.config.security.LoginResult;
import com.sztzjy.forex.trading_trading.config.security.TokenProvider;
import com.sztzjy.forex.trading_trading.util.ResultEntity;
import com.sztzjy.forex.trading_trading.util.RsaUtil;
import com.sztzjy.forex.trading_trading.util.TzApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("api/sysUser")
@RequiredArgsConstructor
public class UserController {
private AuthenticationManagerBuilder authenticationManagerBuilder;
@AnonymousAccess
@OperateLog(description = "用户登录")
@ApiOperation(value = "用户登录",httpMethod = "POST")
@PostMapping("login")
public ResultEntity<LoginResult> login(@ApiParam("用户名")@RequestParam String username,
@ApiParam("加密后的密文")@RequestParam String passwordEncode){
String password;
try {
password = RsaUtil.decryptByPrivateKey(passwordEncode);
} catch (Exception e) {
throw new IllegalArgumentException("密码错误");
}
JwtUser jwtUser = TzApi.foreignExchangeTradingLogin(username, password);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenProvider.createToken(jwtUser);
return new ResultEntity<LoginResult>(LoginResult.create(jwtUser,token));
}
}

@ -0,0 +1,81 @@
package com.sztzjy.forex.trading_trading.util;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class HttpUtils {
// 发送GET请求
public static String sendGet(String url) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
// 发送POST请求
public static String sendPost(String url, String requestBody) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
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);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
}

@ -0,0 +1,125 @@
package com.sztzjy.forex.trading_trading.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA
*/
public class RsaUtil {
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRehqqa1eLnTL3BSRq3zmB+Yw7nLAMAZ0G+FpoGP0eFLc0JVC2P2sfkCJJjH2cOmoLcUFjHfDcHzMNyl4wmNTMeXhpvK3v2ha1ufZnGmoMd9d4+1R/t/pZdxXXzkQMN2012X/KIojluEJmrIXLUM0zjOTABSMlTY6TPfSrmuXyGwIDAQAB";
private static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJF6GqprV4udMvcFJGrfOYH5jDucsAwBnQb4WmgY/R4UtzQlULY/ax+QIkmMfZw6agtxQWMd8NwfMw3KXjCY1Mx5eGm8re/aFrW59mcaagx313j7VH+3+ll3FdfORAw3bTXZf8oiiOW4QmashctQzTOM5MAFIyVNjpM99Kua5fIbAgMBAAECgYBtr3fNiHOQg6z6jLkBj18nvYTbKW+fDdRcfgKEPFsURCBBw+TQFI7rVFxVwgSvN2ffSrw3RErnXOq8ehl8YK8IfPWleMTXkuGB4QDptou3S7aJ4OlK+p5YOsjVEgnzJ3J7gPUYJRGAX59G+EbEnHKvoTQQjlQ4EaFqp77ba+SN+QJBAM1rre1TSSIuZd7biS4d0znVDRA3Zv/AnpmSaLZODU6p70DnPn3WCf5LNJGsS+Bt1xkq/EHzhpspjy/IfJrZOO8CQQC1S/vrpm8+WsXp8FAlvuQ+UOR1UlMs4WMokVMSOcPcgG2Iab8f1UcD9GptjBjORKiloQBpjG/+FXp2VJPd7yGVAkBvmRRAXoLYwwQs8m+wUhuyy3/xU2ftgaOoItYoVHb+SWvlgrt8eY+sSwcgLM57+rBkx+mLmtWB7i4P84deSKyZAkBYJ5FgnXY8MLFJtoOSRwb+0iC0d4pgKVwo7rkhBJubTYt1KE458V/tqVxS1it9qN8EYowrxpDyUIlSnn+kC9IdAkAH6TkJw2tb4N7rIvcZWjd74EBNQdP0FzvZWU2rE6SGqj87yWDKOKGKWu/hz84DCSkyltII4uB+YasJhsgsJnjb";
public static void main(String[] args) throws Exception {
// System.out.println("\n");
// RsaKeyPair keyPair = generateKeyPair();
// System.out.println("公钥:" + keyPair.getPublicKey());
// System.out.println("私钥:" + keyPair.getPrivateKey());
//System.out.println("\n");
String text1 = encryptByPublicKey("@123");
// 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);
}
public static String encryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeBase64String(result);
}
/**
*
*
* @param text
* @return /
* @throws Exception /
*/
public static String encryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(result);
}
public static String decryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
public static String decryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
* RSA
*
* @return /
* @throws NoSuchAlgorithmException /
*/
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString);
}
/**
* RSA
*/
public static class RsaKeyPair {
private final String publicKey;
private final String privateKey;
public RsaKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}

@ -0,0 +1,37 @@
package com.sztzjy.forex.trading_trading.util;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sztzjy.forex.trading_trading.config.security.JwtUser;
public class TzApi {
private final static String API_URL = "http://Cloud.sztzjy.com";
private final static String LOGIN_URL = API_URL + "/api/foreignExchangeTradingLogin";
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) {
throw new IllegalArgumentException("登录失败");
}
JSONObject object = JSONUtil.parseObj(result);
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.setUsername(userName);
return user;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Loading…
Cancel
Save