相关的类:
通过代码生成器导入4个不同的表,并把下载中的public.key放入
依赖:
<dependencies>
<dependency>
<groupId>com.zb</groupId>
<artifactId>shop-goods-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
Application.yml:
server:
port: 9030
spring:
application:
name: shop-goods
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
datasource:
url: jdbc:mysql://localhost:3306/shop_goods?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 1002981655
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
auto-mapping-behavior: FULL #自动映射的配置 属性和数据库列相同不用配置result
global-config: #逻辑删除的配置
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
ResourceServerConfig代码:
package com.zb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)//激活方法上的PreAuthorize注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
//公钥
private static final String PUBLIC_KEY = "public.key";
/***
* 定义JwtTokenStore
* @param jwtAccessTokenConverter
* @return
*/
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
/***
* 定义JJwtAccessTokenConverter
* @return
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
return converter;
}
/**
* 获取非对称加密公钥 Key
*
* @return 公钥 Key
*/
private String getPubKey() {
Resource resource = new ClassPathResource(PUBLIC_KEY);
try {
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return null;
}
}
/***
* Http安全配置,对每个到达系统的http请求链接进行校验
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
//所有请求必须认证通过
http.authorizeRequests()
//下边的路径放行
.antMatchers(
"/tb-user-model/info/**"). //配置地址放行
permitAll()
.anyRequest().
authenticated(); //其他地址需要认证授权
}
}
Swagger2代码:
页面版的postman
package com.zb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author zh
* @ClassName cn.saytime.Swgger2
* @Description
* @date 2017-07-10 22:12:31
*/
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zb.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,http://blog.youkuaiyun.com/saytime")
.termsOfServiceUrl("http://blog.youkuaiyun.com/saytime")
.version("1.0")
.build();
}
}
TokenDecode代码:
package com.zb.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class TokenDecode {
//公钥
private static final String PUBLIC_KEY = "public.key";
private static String publickey = "";
/**
* 获取非对称加密公钥 Key
*
* @return 公钥 Key
*/
public static String getPubKey() {
if (!StringUtils.isEmpty(publickey)) {
return publickey;
}
Resource resource = new ClassPathResource(PUBLIC_KEY);
try {
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
publickey = br.lines().collect(Collectors.joining("\n"));
return publickey;
} catch (IOException ioe) {
return null;
}
}
/***
* 读取令牌数据
*/
public static Map<String, String> dcodeToken(String token) {
//校验Jwt
Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(getPubKey()));
//获取Jwt原始内容
String claims = jwt.getClaims();
return JSON.parseObject(claims, Map.class);
}
/***
* 获取用户信息
* @return
*/
public static Map<String, String> getUserInfo() {
//获取授权信息
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
//令牌解码
return dcodeToken(details.getTokenValue());
}
}
控制器代码:
package com.zb.controller;
import com.zb.dto.BrandDto;
import com.zb.dto.CategoryDto;
import com.zb.dto.SkuDto;
import com.zb.dto.SpuDto;
import com.zb.entity.TbBrandModel;
import com.zb.entity.TbCategoryModel;
import com.zb.entity.TbSkuModel;
import com.zb.entity.TbSpuModel;
import com.zb.service.TbBrandService;
import com.zb.service.TbCategoryService;
import com.zb.service.TbSkuService;
import com.zb.service.TbSpuService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName TbSkuController
* @Description 商品表控制器
* @Author zj
* @Date 2023/03/27 19:56
**/
@RestController
@RequestMapping("/tb-sku-model")
@Api(value = "TbSkuController", tags = {"商品表控制器"})
public class TbSkuController {
@Autowired
public TbSkuService tbSkuModelService;
@Autowired
public TbSpuService tbSpuService;
@Autowired
public TbCategoryService tbCategoryService;
@Autowired
public TbBrandService tbBrandService;
@GetMapping("/info")
public Map<String,Object> info(@RequestParam("skuId") String skuId){
Map<String,Object> data = new HashMap<>();
TbSkuModel tbSkuModel = tbSkuModelService.getById(skuId);
TbSpuModel tbSpuModel = tbSpuService.getById(tbSkuModel.getSpuId());
TbBrandModel tbBrandModel = tbBrandService.getById(tbSpuModel.getBrandId());
TbCategoryModel c1 = tbCategoryService.getById(tbSpuModel.getCategory1Id());
TbCategoryModel c2 = tbCategoryService.getById(tbSpuModel.getCategory2Id());
TbCategoryModel c3 = tbCategoryService.getById(tbSpuModel.getCategory3Id());
SkuDto skuDto = new SkuDto();
SpuDto spuDto = new SpuDto();
BrandDto brandDto = new BrandDto();
CategoryDto cd1 = new CategoryDto();
CategoryDto cd2 = new CategoryDto();
CategoryDto cd3 = new CategoryDto();
BeanUtils.copyProperties(tbSkuModel,skuDto);
BeanUtils.copyProperties(tbSpuModel,spuDto);
BeanUtils.copyProperties(tbBrandModel,brandDto);
BeanUtils.copyProperties(c1,cd1);
BeanUtils.copyProperties(c2,cd2);
BeanUtils.copyProperties(c3,cd3);
data.put("sku",skuDto);
data.put("spu",spuDto);
data.put("brand",brandDto);
data.put("c1",cd1);
data.put("c2",cd2);
data.put("c3",cd3);
return data;
}
}
启动器代码:
package com.zb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableSwagger2
public class GoodsApplication {
public static void main(String[] args) {
SpringApplication.run(GoodsApplication.class, args);
}
}