api网关项目负责转发请求、过滤token等;tao-oms淘宝接口;oms-api公共项目包括登录处理;其他项目暂时没用

This commit is contained in:
启航 2024-01-22 14:35:36 +08:00
parent 98a5985467
commit 6a0884ad32
17 changed files with 252 additions and 137 deletions

View File

@ -61,6 +61,25 @@
<!-- <version>4.13.2</version>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>

View File

@ -3,6 +3,7 @@ package com.qihang.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
/**
* Hello world!
@ -17,4 +18,9 @@ public class Api
System.out.println( "Hello World! Api" );
SpringApplication.run(Api.class, args);
}
// @Bean
// public TokenFilter tokenFilter() {
// return new TokenFilter();
// }
}

View File

@ -0,0 +1,33 @@
package com.qihang.api;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class TokenFilter implements GlobalFilter, Ordered {
private static final String TOKEN_HEADER = "Authorization";
private static final String TOKEN_PREFIX = "Bearer ";
private static final String SECRET_KEY = "mysecretkey235200303325adjjeddd";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst(TOKEN_HEADER);
System.out.println("Token:"+token);
// TODO: 统一鉴权处理
if(!StringUtils.hasText(token)){
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -10000;
}
}

View File

@ -1,13 +1,12 @@
server:
port: 8080
spring:
application:
name: api-service
security:
user:
name: admin
password: password
# security:
# user:
# name: admin
# password: password
basic:
enabled: true
cloud:
@ -22,11 +21,20 @@ spring:
enabled: true
routes:
- id: tao_oms_route
uri: lb://tao-oms # lb 表示从 nacos 中按照名称获取微服务,并遵循负载均衡策略user-service 对应用户微服务应用名
uri: lb://tao-oms
predicates:
- Path=/tao-service/** # 使用断言
- Path=/api/tao-service/**
filters:
- StripPrefix=1 # 使用过滤器
- StripPrefix=2
- id: oms_api_route
uri: lb://oms-api
predicates:
- Path=/api/oms-api/**
filters:
- StripPrefix=2
# - TokenFilter
# default-filters:
# - TokenFilter
# - name: Security # 添加安全过滤器
# args:
# springSecurityFilterChain: # 配置Spring Security过滤器链

View File

@ -26,6 +26,7 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>3.0.2</spring-boot.version>
<spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
<jwt.version>0.11.5</jwt.version>
</properties>
<dependencies>
@ -116,9 +117,23 @@
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
<artifactId>jjwt-api</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>

View File

@ -2,13 +2,11 @@ package com.qihang.oms.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.web.client.RestTemplate;
/**
@ -19,12 +17,12 @@ import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@ComponentScan(basePackages={"com.qihang"})
@SpringBootApplication
public class Api
public class OmsApi
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
SpringApplication.run(Api.class, args);
SpringApplication.run(OmsApi.class, args);
}
@Bean

View File

@ -41,9 +41,16 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
String token = request.getHeader(TOKEN_HEADER);
// String token = exchange.getRequest().getHeaders().getFirst(TOKEN_HEADER);
String token = request.getHeader("Authorization");
log.info("intercept " + request.getRequestURI());
log.info("token: " + token);
if(request.getRequestURI().equals("/login")){
// 登录页面放行
chain.doFilter(request, response);
return;
}
LoginUser loginUser = tokenService.getLoginUser(request);
if (loginUser !=null )
{
@ -51,6 +58,9 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}else {
fallback(" 授权过期!",response);
return;
}
chain.doFilter(request, response);
}

View File

@ -19,7 +19,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>3.0.2</spring-boot.version>
<jwt.version>0.9.1</jwt.version>
<jwt.version>0.11.5</jwt.version>
<spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
</properties>
<dependencies>
@ -46,20 +47,19 @@
<artifactId>spring-tx</artifactId>
<version>6.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>javax.validation</groupId>-->
<!-- <artifactId>validation-api</artifactId>-->
<!-- <version>2.0.1.Final</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--SpringCloud Alibaba nacos 服务发现依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
@ -68,8 +68,22 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.21</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -91,9 +105,23 @@
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<artifactId>jjwt-api</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
@ -121,6 +149,13 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>

View File

@ -3,23 +3,20 @@ package com.qihang.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;
/**
* Hello world!
*
*/
@EnableCaching
@ComponentScan(basePackages = "com.qihang")
//@ComponentScan(basePackages = "com.qihang")
@SpringBootApplication
public class App
public class OmsCoreApplication
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
SpringApplication.run(App.class, args);
SpringApplication.run(OmsCoreApplication.class, args);
}
}

View File

@ -1,81 +1,49 @@
//package com.qihang.core.config;
//
//import com.qihang.core.security.AuthenticationEntryPointImpl;
//import com.qihang.core.security.LogoutSuccessHandlerImpl;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpMethod;
//import org.springframework.security.config.annotation.SecurityBuilder;
//import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
//import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//
//@Configuration
//@EnableWebSecurity
//@EnableMethodSecurity
//public class SecurityConfig {
// @Value("${auth.whitelist:/login}")
// private String[] URL_WHITELIST;
//
// @Autowired
// private AuthenticationEntryPointImpl unauthorizedHandler;
// @Autowired
// private LogoutSuccessHandlerImpl logoutSuccessHandler;
// @Bean
// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//// http
//// // CSRF禁用因为不使用session
//// .csrf().disable()
//// .authorizeRequests()
//// .anyRequest().authenticated()
//// .and()
//// .formLogin()
//// .and()
//// .httpBasic();
// // CSRF禁用因为不使用session
// http.csrf().disable()
// // 禁用HTTP响应标头
// .headers().cacheControl().disable().and()
// // 认证失败处理类
//// .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// // 基于token所以不需要session
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// // 过滤请求
// .authorizeRequests()
// .formLogin(form -> form.
// loginProcessingUrl("/login")
// .usernameParameter("username")
// .passwordParameter("password")
// .successHandler(unauthorizedHandler)
//// .failureHandler(unauthorizedHandler))
// // 对于登录login 注册register 验证码captchaImage 允许匿名访问
// .antMatchers("/login", "/register", "/captchaImage").permitAll()
// // 静态资源可匿名访问
// .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
// .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
// .antMatchers("/test/**").permitAll()
// .antMatchers("/preview/**").permitAll()
// .antMatchers("/h2-console/**").permitAll()
// .antMatchers("/taoapi2/**").permitAll()
// // 除上面外的所有请求全部需要鉴权认证
// .anyRequest().authenticated()
// .and()
// .headers().frameOptions().disable();
// return http.build();
// }
//
// /**
// * 强散列哈希加密实现
// */
// @Bean
// public BCryptPasswordEncoder bCryptPasswordEncoder()
// {
// return new BCryptPasswordEncoder();
// }
//}
package com.qihang.core.config;
import com.qihang.core.security.AuthenticationEntryPointImpl;
import com.qihang.core.security.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
return http.build();
}
/**
* 强散列哈希加密实现
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,13 @@
package com.qihang.core.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/home")
public String home(){
return "oms-core:home";
}
}

View File

@ -10,8 +10,8 @@ import java.util.Collection;
* TODO
*
* @Description
* @Author laizhenghua
* @Date 2023/6/29 22:49
* @Author
* @Date
**/
public class SecurityUser implements UserDetails {
private SysUser userEntity;

View File

@ -30,15 +30,15 @@ import java.util.concurrent.TimeUnit;
public class TokenService
{
// 令牌自定义标识
@Value("${token.header}")
@Value("${token.header:'Authorization'}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
@Value("${token.secret:'mysecretkey235200303325adjjeddd'}")
private String secret;
// 令牌有效期默认30分钟
@Value("${token.expireTime}")
@Value("${token.expireTime:30}")
private int expireTime;
protected static final long MILLIS_SECOND = 1000;

View File

@ -1,4 +0,0 @@
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

View File

@ -0,0 +1,14 @@
spring:
cloud:
nacos:
serverAddr: 127.0.0.1:8848
discovery:
server-addr: 127.0.0.1:8848
config:
import:
- nacos:qihang-oms.yaml?refresh=true
application:
name: oms-core
server:
port: 8083

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class OmsCoreApplicationTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public OmsCoreApplicationTest(String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( OmsCoreApplicationTest.class );
}
/**

View File

@ -1,5 +1,6 @@
package com.qihang.tao.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
@ -16,7 +17,9 @@ public class HomeController {
private String serverName;
@GetMapping(value = "/test/na")
public String get() {
public String get(HttpServletRequest request) {
String token = request.getHeader("Authorization");
System.out.println("tao-api token:"+token);
return serverName;
}