目录
3.5创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)
3.6 创建配置类(配置认证管理器(此对象主要负责对客户端输入的用户信息进行认证)
3.7 创建配置类(完成所有配置的组装,在这个配置类中完成认证授权,JWT令牌签发等配置操作)
4.6创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)
一 设计流程:
分别设计对应的类,使用聚合模式:
1 创建父工程:
1.1添加依赖:
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR9</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.2.6.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <exclusions> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> </exclusion> </exclusions> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> </dependencies>
下面为子工程:
1.UI(客户端设计)
2.网关设计(Gatway)
2.1 创建启动类
2.2.添加依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!--网关层面的sentinel限流--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId> </dependency> </dependencies>
2.3 添加配置文件:
配件文件的名字为bootstrap.yml
server: port: 9000 spring: application: name: sca-resource-gateway cloud: nacos: discovery: server-addr: localhost:8848 config: server-addr: localhost:8848 file-extension: yml gateway: discovery: locator: enabled: true routes: - id: router01 uri: lb://sca-resource predicates: - Path=/sca/resource/upload/** filters: - StripPrefix=1 - id: router02 uri: lb://sca-auth predicates: #- Path=/auth/login/** #没要令牌之前 - Path=/auth/oauth/** #微服务架构下,需要令牌 filters: - StripPrefix=1 globalcors: #跨域配置 corsConfigurations: '[/**]': allowedOrigins: "*" allowedHeaders: "*" allowedMethods: "*" allowCredentials: true sentinel: #限流设计 transport: dashboard: localhost:8180 eager: true
2.4 配置类
解决关于跨域问题
package com.jt; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; @Configuration public class CorsFilterConfig { @Bean public CorsWebFilter corsWebFilter(){ //构建基于url方式的配置 UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource(); //跨域配置 CorsConfiguration config=new CorsConfiguration(); //允许所以的跨域ip :port config.addAllowedOrigin("*"); //请求请求头跨域 config.addAllowedHeader("*"); //所有的请求方式跨域post/get/.. config.addAllowedMethod("*"); //允许携带有效的cookie进行跨域 config.setAllowCredentials(true); source.registerCorsConfiguration("/**",config); return new CorsWebFilter(source); } }
2.5创建配置类(自定义限流结果)
package com.jt.config;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class GatewayConfig {
public GatewayConfig(){
//自定义限流结果
GatewayCallbackManager.setBlockHandler((
serverWebExchange, throwable) ->{
//构建响应数据
Map<String,Object> map=new HashMap<>();
map.put("state",429);
map.put("message","two many request");
//基于alibaba 的fastjson将对象转换为json
String jsonStr= JSON.toJSONString(map);//fastjson
//创建Mono对象,将结果响应到客户端
return ServerResponse.ok().body(Mono.just(jsonStr),
String.class);//String.class表示响应数据类型
//WebFlux
});
}
}
3 认证安全模块(auth)
3.1 添加jar包
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>
3.2 创建配置文件
配置文件名为bootstrap.yml
server:
port: 8071
spring:
application:
name: sca-auth
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
3.3 创建启动类
3.4 创建封装类(对用户信息进行封装)对feign接口的调用
package com.jt.auth.service;
import com.jt.auth.feign.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 登录时用户信息的获取和封装会在此对象进行实现,
* 在页面上点击登录按钮时,会调用这个对象的loadUserByUsername方法,
* 页面上输入的用户名会传给这个方法的参数
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private RemoteUserService remoteUserService;
//UserDetails用户封装用户信息(认证和权限信息)
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//1.基于用户名查询用户信息(用户名,用户状态,密码,....)
com.jt.auth.pojo.User user=
remoteUserService.selectUserByUsername(username);
//2.查询用户权限信息(后面会访问数据库)
List<String> permissions=
remoteUserService.selectUserPermissions(user.getId());
System.out.println("permissions="+permissions);
List<GrantedAuthority> authorities =
AuthorityUtils.createAuthorityList(//
permissions.toArray(new String[]{}));
//3.对用户信息进行封装
return new User(username,user.getPassword(),authorities);
}
}
3.5创建配置类(创建JWT令牌配置类,基于这个类实现令牌对象的创建和解析.)
package com.jt.auth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;