package com.czxy.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.joda.time.DateTime; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; public class JWTUtil { public static Claims parseToken(String token,String key) { if ("".equals(token)) { return null; } try { return Jwts.parser() .setSigningKey(DatatypeConverter.parsebase64Binary(key)) .parseClaimsJws(token).getBody(); } catch (Exception ex) { return null; } } public static String createToken(Integer userId,String username,String key, int expireMinutes) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parsebase64Binary(key); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //添加构成JWT的参数 JwtBuilder builder = Jwts.builder() // .setHeaderParam("type", "JWT") // .setSubject(userId.toString()) .claim("userId", userId) // 设置载荷信息 .claim("username",username) .claim("age",23) .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())// 设置超时时间 .signWith(signatureAlgorithm, signingKey); //生成JWT return builder.compact(); } public static void main(String[] args) { String token = JWTUtil.createToken(1, "zhangsan","admin", 30); System.out.println(token); Claims claims = JWTUtil.parseToken(token, "admin"); System.out.println(); } }1.2:vo包下baseResult.java
package com.czxy.vo; import java.util.HashMap; import java.util.Map; public class baseResult1.3:pom.xml{ //成功状态码 public static final int OK = 1; //失败状态码 public static final int ERROR = 0; //返回码 private Integer code; //返回消息 private String message; //存放数据 private T data; //其他数据 private Map other = new HashMap<>(); public baseResult() { } public baseResult(Integer code, String message) { this.code = code; this.message = message; } public baseResult(Integer code, String message, T data) { this.code = code; this.message = message; this.data = data; } public static baseResult ok(String message){ return new baseResult(baseResult.OK , message); } public static baseResult ok(String message, Object data){ return new baseResult(baseResult.OK , message, data ); } public static baseResult error(String message){ return new baseResult(baseResult.ERROR , message); } public baseResult append(String key , Object msg){ other.put(key , msg); return this; } public Integer getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } public Map getOther() { return other; } }
2、pojo模块 2.1:pom.xmlteacher-school-mybatis-puls org.example 1.0-SNAPSHOT 4.0.0 jwt-commonio.jsonwebtoken jjwtjoda-time joda-timeorg.projectlombok lombokcom.baomidou mybatis-plus-boot-starter3.4.0
3、gateway模块 3.1、filters包下的JWTFilter.javateacher-school-mybatis-puls org.example 1.0-SNAPSHOT 4.0.0 jwt-pojoorg.projectlombok lombokorg.springframework spring-context5.3.9 com.fasterxml.jackson.core jackson-annotations2.12.4 com.baomidou mybatis-plus-boot-starter3.4.0
package com.czxy.gateway.filters; import com.czxy.common.util.JWTUtil; import io.jsonwebtoken.Claims; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component @Order(-1) public class JWTFilter implements GlobalFilter { @Override public Mono3.2、bootstrap.ymlfilter(ServerWebExchange exchange, GatewayFilterChain chain) { String path = exchange.getRequest().getURI().getPath(); if (path.contains("/auth")||path.contains("/sendSms")||path.contains("/regist")) { System.out.println("无需登录,直接放行"); return chain.filter(exchange); } String token = exchange.getRequest().getHeaders().getFirst("authorization"); if (token != null && !token.equals("")) { Claims claims = JWTUtil.parseToken(token, "user"); System.out.println(claims); if (claims != null) ; { return chain.filter(exchange); } } exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); return exchange.getResponse().setComplete(); } }
server: port: 10010 # 网关端口 spring: application: name: gateway # 服务名称 cloud: nacos: server-addr: localhost:8848 # nacos地址 gateway: routes: # 网关路由配置 - id: school-service uri: lb://schoolservice predicates: - Path=/school/** globalcors: # 全局的跨域处理 add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题 corsConfigurations: '[ @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class); } }4.1、feign-api
5、consumer 5.1 application.ymlteacher-school-mybatis-puls org.example 1.0-SNAPSHOT 4.0.0 feign-api8 8 org.springframework.cloud spring-cloud-starter-openfeignorg.example jwt-pojo1.0-SNAPSHOT com.fasterxml.jackson.core jackson-annotations2.11.4
spring: datasource: url: jdbc:mysql://localhost:3306/cloud_teacher?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver cloud: nacos: discovery: cluster-name: HZ # namespace: c8a2e6da-76dd-4558-a122-d431d1eaf09b # 命名空间,填ID # 临时实例 # ephemeral: false mybatis: type-aliases-package: com.czxy.pojo configuration: map-underscore-to-camel-case: true # 设置日志级别(方式一) feign: httpclient: enabled: true # 开启feign对HttpClient的支持 max-connections: 200 # 最大的连接数 max-connections-per-route: 50 # 每个路径的最大连接数 # client: # config: # default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置 # loggerLevel: FULL # 日志级别 #eureka: # client: # service-url: # defaultZone: http://127.0.0.1:10086/eureka # instance: # prefer-ip-address: true # instance-id: 127.0.0.1:${server.port} userservice: ribbon: NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # 负载均衡规则 #ribbon: # eager-load: # enabled: true # clients: userservice5.2、bootstrap.yml
server: port: 9010 spring: application: name: teacherservice profiles: active: dev cloud: nacos: server-addr: localhost:8848 config: file-extension: yaml mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #输出日志5.3、pom.xml
6、producer模块: 6.1、application.ymlteacher-school-mybatis-puls org.example 1.0-SNAPSHOT 4.0.0 teacher-serviceorg.example jwt-pojo1.0-SNAPSHOT org.example jwt-common1.0-SNAPSHOT org.springframework.boot spring-boot-starter-webmysql mysql-connector-javacom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-configorg.springframework spring-tx5.2.13.RELEASE org.example feign-api1.0-SNAPSHOT com.baomidou mybatis-plus-boot-starter3.4.0 org.apache.commons commons-lang33.11 org.springframework.boot spring-boot-maven-plugin
spring: datasource: url: jdbc:mysql://localhost:3306/cloud_school?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver cloud: nacos: discovery: cluster-name: HZ # namespace: c8a2e6da-76dd-4558-a122-d431d1eaf09b # 命名空间,填ID # 临时实例 # ephemeral: false mybatis: type-aliases-package: com.czxy.pojo configuration: map-underscore-to-camel-case: true # 设置日志级别(方式一) feign: httpclient: enabled: true # 开启feign对HttpClient的支持 max-connections: 200 # 最大的连接数 max-connections-per-route: 50 # 每个路径的最大连接数 # client: # config: # default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置 # loggerLevel: FULL # 日志级别 #eureka: # client: # service-url: # defaultZone: http://127.0.0.1:10086/eureka # instance: # prefer-ip-address: true # instance-id: 127.0.0.1:${server.port} userservice: ribbon: NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # 负载均衡规则 #ribbon: # eager-load: # enabled: true # clients: userservice6.2、bootstrap.yml
server: port: 9020 spring: application: name: schoolservice profiles: active: dev cloud: nacos: server-addr: localhost:8848 config: file-extension: yaml rabbitmq: host: 192.168.88.130 # 主机名 port: 5672 # 端口 virtual-host: / # 虚拟主机 username: itcast # 用户名 password: 123321 # 密码 redis: host: localhost port: 6379 database: 0 jedis: pool: max-idle: 8 min-idle: 0 max-active: 8 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #输出日志6.3、pom.xml
teacher-school-mybatis-puls org.example 1.0-SNAPSHOT 4.0.0 school-serviceorg.example jwt-pojo1.0-SNAPSHOT org.example jwt-common1.0-SNAPSHOT org.springframework.boot spring-boot-starter-webmysql mysql-connector-javacom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-configorg.springframework spring-tx5.2.13.RELEASE org.springframework.boot spring-boot-starter-amqporg.springframework.boot spring-boot-starter-data-rediscom.baomidou mybatis-plus-boot-starter3.4.0 org.apache.commons commons-lang33.11 org.springframework.boot spring-boot-maven-plugin
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)