Commit a51fbed5 by zhoujinghao

加入jwt相关代码

1 parent 783a34bc
......@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8001/swagger-ui.html
eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
spring.datasource.url=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=Moxi123#
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
\ No newline at end of file
......@@ -89,13 +89,18 @@
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.10.RELEASE</version>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
<exclusions>
<exclusion>
<artifactId>bcprov-jdk15on</artifactId>
<groupId>org.bouncycastle</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
......
package org.nafmii.auth;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Header;
import com.auth0.jwt.interfaces.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.nafmii.entity.AppUser;
import org.nafmii.exception.JwtException;
import org.nafmii.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
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 String APPSECRET_KEY = "congge_secret";
private static final String ROLE_CLAIMS = "rol";
public static String generateJsonWebToken(AppUser user) {
if (user.getId() == null || user.getUserName() == null ) {
return null;
}
Map<String,Object> map = new HashMap<>();
map.put(ROLE_CLAIMS, "rol");
String token = Jwts
.builder()
.setSubject(SUBJECT)
.setClaims(map)
.claim("id", user.getId())
.claim("name", user.getUserName())
.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 {
final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
     * 获取用户名
     * @param token
     * @return
     */
public static String getUsername(String token){
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("username").toString();
}
/**
     * 获取用户角色
     * @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());
}
public static void main(String[] args) {
String name = "acong";
String role = "rol";
String token = createToken(name,role);
System.out.println(token);
Claims claims = checkJWT(token);
System.out.println(claims.get("username"));
System.out.println(getUsername(token));
System.out.println(getUserRole(token));
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);
            
            
            
        }
    }*/
}
package org.nafmii.controller;
import org.nafmii.result.Result;
import org.nafmii.service.UserService;
import org.nafmii.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:10
* @ClassName:
* @version:
* @remark:
*/
@RestController
@RequestMapping("/auth")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
@ResponseBody
public Result<UserVO> login (){
Result<UserVO> login = userService.login();
return login;
}
}
package org.nafmii.entity;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class AppUser implements Serializable {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHeadPicture() {
return headPicture;
}
public void setHeadPicture(String headPicture) {
this.headPicture = headPicture;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getFigerprintFalg() {
return figerprintFalg;
}
public void setFigerprintFalg(String figerprintFalg) {
this.figerprintFalg = figerprintFalg;
}
public String getFaceidFalg() {
return faceidFalg;
}
public void setFaceidFalg(String faceidFalg) {
this.faceidFalg = faceidFalg;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getIsEnable() {
return isEnable;
}
public void setIsEnable(String isEnable) {
this.isEnable = isEnable;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userName=").append(userName);
sb.append(", loginPwd=").append(loginPwd);
sb.append(", realName=").append(realName);
sb.append(", phone=").append(phone);
sb.append(", birthday=").append(birthday);
sb.append(", email=").append(email);
sb.append(", headPicture=").append(headPicture);
sb.append(", nationality=").append(nationality);
sb.append(", unitName=").append(unitName);
sb.append(", openId=").append(openId);
sb.append(", figerprintFalg=").append(figerprintFalg);
sb.append(", faceidFalg=").append(faceidFalg);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", isEnable=").append(isEnable);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
package org.nafmii.entity;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class CenterRole implements Serializable {
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "角色名称")
private String rName;
@ApiModelProperty(value = "创建时间")
private Date creatTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1禁用")
private String isEnable;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public Date getCreatTime() {
return creatTime;
}
public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getIsEnable() {
return isEnable;
}
public void setIsEnable(String isEnable) {
this.isEnable = isEnable;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", rName=").append(rName);
sb.append(", creatTime=").append(creatTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", isEnable=").append(isEnable);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
package org.nafmii.service;
import org.nafmii.result.Result;
import org.nafmii.vo.UserVO;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:
* @version:
* @remark:
*/
public interface UserService {
Result<UserVO> login();
}
package org.nafmii.service.impl;
import org.nafmii.auth.JwtUtils;
import org.nafmii.result.Result;
import org.nafmii.service.UserService;
import org.nafmii.vo.UserAndRoleVo;
import org.nafmii.vo.UserVO;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:
* @version:
* @remark:
*/
@Service
public class UserServiceImpl implements UserService {
@Override
public Result<UserVO> login() {
Result result = new Result();
//假设验证数据通过
UserVO userVO = new UserVO();
userVO.setPassword("zzz");
userVO.setUserName("zzz");
List<UserAndRoleVo> roleList =new ArrayList<>();
UserAndRoleVo roleVo = new UserAndRoleVo();
roleVo.setRole("a");
roleVo.setRole("b");
roleList.add(roleVo);
userVO.setAuthorities(roleList);
StringBuilder sbf = new StringBuilder();
for (UserAndRoleVo role:roleList
) {
sbf=sbf.append(role.getRole()+",");
}
//处理字符串
String sRole = sbf.toString();
String substring = sRole.substring(0, sRole.lastIndexOf(","));
String token = JwtUtils.createToken(userVO.getUserName(),substring);
userVO.setToken(token);
result.setData(userVO);
return result;
}
}
package org.nafmii.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.entity.CenterRole;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 9:06
* @ClassName:
* @version:
* @remark:
*/
@Data
public class UserAndRoleVo {
private Long id;
private String userName;
private String password;
@ApiModelProperty("角色名称")
private String Role;
}
package org.nafmii.vo;
import lombok.Data;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
public class UserVO {
private String userName;
private String password;
private String token;//角色集合
private List<UserAndRoleVo> authorities;
}
......@@ -9,8 +9,8 @@ eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8002/swagger-ui.html
eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
spring.datasource.url=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=Moxi123#
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
\ No newline at end of file
package org.nafmii.exception;
public class JwtException extends RuntimeException {
public JwtException() {
super();
}
public JwtException(String message) {
super(message);
}
public JwtException(String message, Throwable cause) {
super(message, cause);
}
public JwtException(Throwable cause) {
super(cause);
}
protected JwtException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
......@@ -12,7 +12,7 @@ public class Result<T> {
private Long code;
private String message;
private T data;
public Result(){};
public Result(Long code, String message, T data) {
this.code = code;
this.message = message;
......
package org.nafmii.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* Created by zhangzhenfang on 2018/6/5.
*/
public class JsonUtils {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
};
public static String toJsonString(Object object) {
return JSON.toJSONString(object, config, features);
}
// public static String toJSONNoFeatures(Object object) {
// return JSON.toJSONString(object, config);
// }
public static Object parse(String text) {
return JSON.parse(text);
}
public static <T> T parse(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
}
......@@ -39,6 +39,15 @@
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!--接口文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies>
<build>
......
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.connectionURL=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.userId=root
jdbc.password=123456
\ No newline at end of file
jdbc.password=Moxi123#
\ No newline at end of file
......@@ -37,7 +37,7 @@
<javaClientGenerator type="XMLMAPPER" targetPackage="org.nafmii.nafmiimbg.mapper"
targetProject="nafmii-mbg\src\main\java"/>
<!--生成全部表tableName设为%-->
<table tableName="%">
<table tableName="CENTER_ROLE">
<!--<generatedKey column="id" sqlStatement="MySql" identity="true"/>-->
</table>
</context>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!