Commit 6739a572 by ypenglv

新增工具类

1 parent 7e951727
......@@ -7,6 +7,7 @@ import org.nafmii.app.user.dto.RegisterDto;
import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -45,6 +46,7 @@ public class UserController {
@PostMapping("/userLogin")
@ResponseBody
public ApiResponse<UserVO> login (@RequestBody LoginDto loginDto){
Long userId = RequestUtils.getUserId();
ApiResponse<UserVO> login = userService.userLogin(loginDto);
return login;
}
......
......@@ -9,6 +9,7 @@ import org.nafmii.app.user.entity.AppUserPO;
import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserAndRoleVo;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.constant.HttpClientHeaderEnum;
import org.nafmii.common.exception.BusinessException;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.GuavaUtil;
......@@ -24,7 +25,9 @@ import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
......@@ -74,7 +77,9 @@ public class UserServiceImpl implements UserService {
//处理字符串
String sRole = sbf.toString();
String substring = sRole.substring(0, sRole.lastIndexOf(","));
String token = JwtUtils.createToken(userVO.getUserName(),substring);
Map<String,Object> map = new HashMap<>();
map.put(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode(),userVO.getId());
String token = JwtUtils.generateJsonWebToken(map);
// userVO.setToken(token);
result.setData(userVO);
return result;
......@@ -157,7 +162,9 @@ public class UserServiceImpl implements UserService {
throw new BusinessException("请先注册");
}
}
String token = JwtUtils.createToken(loginDto.getPhone(),null);
Map<String,Object> map = new HashMap<>();
map.put(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode(),userVo.getId());
String token = JwtUtils.generateJsonWebToken(map);
userVo.setAuthorization(token);
ApiResponse apiResponse =new ApiResponse();
apiResponse.setData(userVo);
......
......@@ -17,6 +17,7 @@
<httpClient.version>4.5.3</httpClient.version>
<fastjson.version>1.2.58</fastjson.version>
<ojdbc.version>10.2.0.4</ojdbc.version>
<jjwt.version>0.9.1</jjwt.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
......@@ -206,11 +207,6 @@
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
......
......@@ -7,9 +7,8 @@ public enum HttpClientHeaderEnum {
* 系统自定义请求header参数
*/
USER_HEADER_USER_ID("userId", "用户ID"),
USER_HEADER_USER_TOKEN("token", "用户token"),
USER_HEADER_MODE("mode", "设备:PC,APP,PAD"),
;
USER_HEADER_USER_TOKEN("Authorization", "用户token"),
USER_HEADER_MODE("mode", "设备:PC,APP,PAD");
HttpClientHeaderEnum(String code, String name){
this.code = code;
......
......@@ -6,33 +6,33 @@ public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer statusCode;
private Integer status;
public BusinessException() {
super ();
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
this.status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
public BusinessException(String message) {
super (message);
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
this.status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
public BusinessException(Integer statusCode, String message) {
super (message);
this.statusCode = statusCode;
this.status = statusCode;
}
public BusinessException(Long statusCode, String message) {
super (message);
this.statusCode = Integer.parseInt(statusCode.toString());
this.status = Integer.parseInt(statusCode.toString());
}
public Integer getStatusCode() {
return statusCode;
return status;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
this.status = statusCode;
}
}
......@@ -3,62 +3,33 @@ package org.nafmii.common.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.nafmii.common.vo.UserJwtVO;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.common.constant.HttpClientHeaderEnum;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JwtUtils {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String SUBJECT = "congge";
public static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7;
public static final long EXPIRITION = 1000 * 60 * 60 * 24 * 7;
// public static final long EXPIRITION = 1000 * 60;
public static final String APPSECRET_KEY = "congge_secret";
public static final String APPSECRET_KEY = "qwertyuiop123456780";
private static final String ROLE_CLAIMS = "rol";
public static String generateJsonWebToken(UserJwtVO user) {
if (user.getId() == null || user.getUserName() == null ) {
public static String generateJsonWebToken(Map<String,Object> param) {
if (param.isEmpty()) {
return null;
}
Map<String,Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, "rol");
String token = Jwts
return Jwts
.builder()
.setSubject(SUBJECT)
.setClaims(map)
.claim("id", user.getId())
.claim("name", user.getUserName())
.claim(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode(), param.get(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
.signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
return token;
}
/**
     * 生成token
     * @param username
     * @param role
     * @return
     */
public static String createToken(String username,String role) {
Map<String,Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, role);
String token = Jwts
.builder()
.setSubject(username)
.setClaims(map)
.claim("username",username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
.signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
return token;
}
public static Claims checkJWT(String token) {
try {
......@@ -71,85 +42,36 @@ public class JwtUtils {
}
/**
     * 获取用户
     * 获取用户信息
     * @param token
     * @return
     */
public static String getUsername(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("username").toString();
}
public static Claims getUserInfo(String token){
return Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
/**
     * 获取用户角色
     * @param token
     * @return
     */
public static String getUserRole(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("rol").toString();
}
/**
   * 是否过期
   * @param token
   * @return
   */
public static boolean isExpiration(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.getExpiration().before(new Date());
try {
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.getExpiration().before(new Date());
} catch (Exception e){
log.error("令牌已过期");
return true;
}
}
public static void main(String[] args) {
String name = "acong";
String role = "rol";
String token = createToken(name,role);
Map<String,Object> map = new HashMap<>();
map.put("userId",12312321313L);
String token = generateJsonWebToken(map);
System.out.println(token);
Claims claims = checkJWT(token);
System.out.println(claims.get("username"));
System.out.println(getUsername(token));
System.out.println(getUserRole(token));
Claims claims = getUserInfo(token);
System.out.println(claims.get(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()));
System.out.println(isExpiration(token));
}
/**
     * eyJhbGciOiJIUzI1NiJ9.
     * eyJzdWIiOiJjb25nZ2UiLCJpZCI6IjExMDExIiwibmFtZSI6Im51b3dlaXNpa2kiLCJpbWciOiJ3d3cudW9rby5jb20vMS5wbmciLCJpYXQiOjE1NTQ5OTI1NzksImV4cCI6MTU1NTU5NzM3OX0.
     * 6DJ9En-UBcTiMRldZeevJq3e1NxJgOWryUyim4_-tEE
     * 
     * @param args
     */
/*public static void main(String[] args) {
        Users user = new Users();
        user.setId("11011");
        user.setUserName("nuoweisiki");
        user.setFaceImage("www.uoko.com/1.png");
        String token = generateJsonWebToken(user);
        System.out.println(token);
        Claims claims = checkJWT(token);
        if (claims != null) {
            String id = claims.get("id").toString();
            String name = claims.get("name").toString();
            String img = claims.get("img").toString();
            
            String rol = claims.get("rol").toString();
            System.out.println("id:" + id);
            System.out.println("name:" + name);
            System.out.println("img:" + img);
            
            System.out.println("rol:" + rol);
            
            
            
        }
    }*/
}
......@@ -26,7 +26,9 @@ public class RequestUtils {
}
public static Long getUserId(){
String userId = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode());
//token 获取用户信息
String token = getToken();
String userId = JwtUtils.getUserInfo(token).get(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()).toString();
if (!StringUtils.isEmpty(userId)){
try {
return Long.valueOf(userId);
......
......@@ -6,7 +6,6 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@SuppressWarnings("unchecked")
......@@ -35,9 +34,4 @@ public class SpringUtils implements ApplicationContextAware {
return requestAttrs.getRequest();
}
// public static String getMessage(String code, Object... args) {
// LocaleResolver localeResolver = getBean(LocaleResolver.class);
// Locale locale = localeResolver.resolveLocale(getCurrentReq());
// return applicationContext.getMessage(code, args, locale);
// }
}
package org.nafmii.gateway.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nafmii.common.exception.BusinessException;
import org.nafmii.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* Created by zhangzhenfang on 2018/4/17.
// */
......@@ -42,7 +49,8 @@ public class AccessFilter implements GlobalFilter, Ordered {
String token = exchange.getRequest().getHeaders().getFirst(JwtUtils.TOKEN_HEADER);
if (StringUtils.isBlank(token)){
//没有token
throw new BusinessException("请登录");
return interceptMsg(exchange,"token不能为空");
}else {
try {
//解析token
......@@ -51,21 +59,45 @@ public class AccessFilter implements GlobalFilter, Ordered {
if (!expiration){ //签名验证通过
return chain.filter(exchange);
}else {
throw new BusinessException("认证无效");
return interceptMsg(exchange,"认证过期");
}
} catch (Exception e) {
log.error("检查token时异常: " + e);
if (e.getMessage().contains("JWT expired")){
throw new BusinessException("认证过期");
return interceptMsg(exchange,"认证过期");
}
else{
throw new BusinessException("认证失败");
return interceptMsg(exchange,"无效令牌");
}
}
}
}
/**
* 自定义错误
*
* @param exchange 请求
* @param msg 消息
* @return
*/
public static Mono<Void> interceptMsg(ServerWebExchange exchange, String msg) {
Map<String, Object> resultMap = new HashMap<>(8);
resultMap.put("status", 401);
resultMap.put("statusText", StringUtils.isBlank(msg) ? "服务异常!" : msg);
resultMap.put("data",null);
return Mono.defer(() -> {
byte[] bytes = new byte[0];
try {
bytes = new ObjectMapper().writeValueAsBytes(resultMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
@Override
public int getOrder() {
return -999;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!