pull/60/head
diaobisong 2 years ago
parent abcb26e260
commit f11266bf55

@ -52,6 +52,13 @@
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
</dependencies>

@ -0,0 +1,17 @@
package com.java3y.austin.web.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Set;
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtConfig {
private String key;
}

@ -0,0 +1,50 @@
package com.java3y.austin.web.controller;
import com.java3y.austin.web.annotation.AustinAspect;
import com.java3y.austin.web.annotation.AustinResult;
import com.java3y.austin.web.config.JwtConfig;
import com.java3y.austin.web.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
*
*
* @author 3y
*/
@Slf4j
@AustinAspect
@RequestMapping("/user")
@RestController
@Api("用户controller")
public class UserController {
@Autowired
private JwtConfig jwtConfig;
/**
* @param creator
* @return
*/
@GetMapping("/login")
@ApiOperation("登录")
@AustinResult
public ResponseEntity<Map> login(String creator) {
Map resultMap = new HashMap();
resultMap.put("creator", creator);
String token = JwtUtil.createToken(creator, jwtConfig.getKey(), 24 * 60 * 60);
resultMap.put("token", token);
return ResponseEntity.ok(resultMap);
}
}

@ -0,0 +1,52 @@
package com.java3y.austin.web.enums;
public enum ReturnCodeEnum {
// 200
SUCCESS(200, "成功"),
// 400
PARAM_ERROR(4001, "参数错误"),
DATA_ALREADY_IN_USE(4002, "数据已经被使用"),
PASSWORD_ERROR(4003, "密码错误"),
// 403
FORBIDDEN(4031, "没有权限"),
TOKEN_EXPIRED(4032, "token过期"),
TOKEN_INVALID(4033, "token无效"),
ACCOUNT_INVALID(4034, "账号已经失效"),
TOO_MANY_REQUEST(4035, "请求太频繁了,请稍后再试"),
USER_ACCOUNT_INVALID(4036, "账户无效"),
BALANCE_NOT_ENOUGH(4037, "余额不足"),
// 404
NOT_FOUND(4041, "not found"),
DATA_NOT_EXIST(4042, "数据不存在"),
LOGGED_USER_NOT_AVAILABLE(4043, "未获取到登录用户"),
USER_NOT_EXISTS(4044, "用户不存在"),
// 500
SYSTEM_ERROR(5001, "系统异常"),
BUSINESS_ERROR(5002, "业务异常"),
DATA_ALREADY_EXISTS(5003, "数据已经存在"),
LOGIN_FAIL(5004, "登录失败"),
;
ReturnCodeEnum(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
private final Integer code;
private final String desc;
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
}

@ -0,0 +1,31 @@
package com.java3y.austin.web.exception;
import com.java3y.austin.web.enums.ReturnCodeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class BusinessException extends RuntimeException {
private ReturnCodeEnum returnCodeEnum;
public BusinessException(String message) {
super(message);
}
public BusinessException(ReturnCodeEnum returnCodeEnum) {
super(returnCodeEnum.getDesc());
this.returnCodeEnum = returnCodeEnum;
}
public BusinessException(String message, ReturnCodeEnum returnCodeEnum) {
super(message);
this.returnCodeEnum = returnCodeEnum;
}
public ReturnCodeEnum getReturnCodeEnum() {
return ReturnCodeEnum.BUSINESS_ERROR;
}
}

@ -0,0 +1,50 @@
package com.java3y.austin.web.interceptor;
import com.alibaba.fastjson.JSON;
import com.java3y.austin.web.config.JwtConfig;
import com.java3y.austin.web.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private JwtConfig jwtConfig;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(request.getRequestURI().startsWith("/actuator") || request.getRequestURI().startsWith("/user/login")) {
return true;
}
String jwtToken = request.getHeader("Authorization");
if (ObjectUtils.isEmpty(jwtToken)) {
throw new RuntimeException("need token");
}
Claims claims = JwtUtil.decodeAndVerify(jwtToken, jwtConfig.getKey());
String subject = claims.getSubject();
String creator = StringUtils.defaultIfEmpty(JSON.parseObject(subject).getString("creator"), JSON.parseObject(subject).getString("userId"));
request.setAttribute("creator", creator);
log.info("request {} with creator {} ", request.getRequestURI(), creator);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}

@ -0,0 +1,29 @@
package com.java3y.austin.web.utils;
import com.java3y.austin.web.enums.ReturnCodeEnum;
import com.java3y.austin.web.exception.BusinessException;
import io.jsonwebtoken.*;
import java.util.Date;
public class JwtUtil {
public static Claims decodeAndVerify(String token, String key) {
try {
return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
} catch (ExpiredJwtException ex) {
throw new BusinessException(ReturnCodeEnum.TOKEN_EXPIRED);
} catch (Exception ex) {
throw new BusinessException(ReturnCodeEnum.TOKEN_INVALID);
}
}
public static String createToken(String subject, String key, long ttl) {
JwtBuilder jwtBuilder = Jwts.builder()
.setSubject(subject)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + ttl * 1000))
.signWith(SignatureAlgorithm.HS256, key);
return jwtBuilder.compact();
}
}

@ -14,10 +14,10 @@ austin.nacos.enabled=false
austin.rule.engine.enabled=true
# TODO if windows os and need upload file to send message ,replace path !
austin.business.upload.crowd.path=/Users/3y/temp
austin.business.upload.crowd.path=/tmp
# TODO if [login use officialAccount] switch [optional], if austin.login.official.account.enable=true
austin.login.official.account.enable=true
austin.login.official.account.enable=false
austin.login.official.account.appId=wx27f83ca10e06b325
austin.login.official.account.secret=203299484df873a18621d076db46fa99
austin.login.official.account.token=austin123

@ -134,3 +134,4 @@ management.health.rabbit.enabled=false
server.shutdown=graceful
########################################## system end ##########################################
jwt.key: 3a79fb4970284e1b849b3ff26e7e1248

Loading…
Cancel
Save