#yyds干货盘点# springboot整合Oauth2,GateWay实现网关登录授权验证

宝剑锋从磨砺出,梅花香自苦寒来。这篇文章主要讲述#yyds干货盘点# springboot整合Oauth2,GateWay实现网关登录授权验证相关的知识,希望能为你提供帮助。
springboot整合Oauth2,GateWay实现登录授权验证。在??Spring cloud Oauth2的密码模式使用JWT方式实现登录验证授权??基础上进行修改。
1.代码实现
oauth2-service, oauth2-client服务代码不做改动,这部分代码可以查看??#yyds干货盘点# Spring cloud Oauth2的密码模式使用JWT方式实现登录验证授权??
1新增oauth2-gateway网关服务
添加依赖

< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter< /artifactId>
< /dependency>
< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter-test< /artifactId>
< scope> test< /scope>
< /dependency>
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-starter-gateway< /artifactId>
< version> 3.0.4< /version>
< /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>
< !--fegin组件-->
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-starter-openfeign< /artifactId>
< version> 3.0.2< /version>
< /dependency>
< !-- Feign Client for loadBalancing -->
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-loadbalancer< /artifactId>
< version> 3.0.2< /version>
< /dependency>
< !--客户端负载均衡loadbalancer-->
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-starter-loadbalancer< /artifactId>
< /dependency>

yml配置
server:
port: 8101
spring:
application:
name: oauth2-gateway #服务名
profiles:
active: dev #环境设置
cloud:
gateway:
routes:
# 透传服务
- id: oauth2-server #设置路由id(理论上是可以随便写的)
uri: lb://oauth2-server#设置路由的url lb://nacos服务注册名称
predicates:
- Path=/server-api/** #路径匹配规则
filters:
- StripPrefix=1
- id: oauth2-client
uri: lb://oauth2-client
predicates:
- Path=/client-api/**
filters:
- StripPrefix=1

跨域配置
@Configuration
public class CorsConfig
@Bean
public CorsWebFilter corsFilter()
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);



2新增oauth2-web前端页面服务
可以参考??#yyds干货盘点# springboot整合thymeleaf??
添加依赖
< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter< /artifactId>
< /dependency>
< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter-test< /artifactId>
< scope> test< /scope>
< /dependency>
< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter-web< /artifactId>
< /dependency>
< dependency>
< groupId> org.springframework.boot< /groupId>
< artifactId> spring-boot-starter-thymeleaf< /artifactId>
< /dependency>
< !--服务注册-->
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-starter-alibaba-nacos-discovery< /artifactId>
< version> 0.2.1.RELEASE< /version>
< /dependency>
< !--服务调用-->
< dependency>
< groupId> org.springframework.cloud< /groupId>
< artifactId> spring-cloud-starter-openfeign< /artifactId>
< /dependency>
< dependency>
< groupId> com.squareup.okhttp3< /groupId>
< artifactId> okhttp< /artifactId>
< version> 3.14.2< /version>
< /dependency>
< dependency>
< groupId> io.jsonwebtoken< /groupId>
< artifactId> jjwt< /artifactId>
< version> 0.9.1< /version>
< /dependency>

yml配置
server:
port: 8102
spring:
application:
name: oauth2-web #服务名
thymeleaf: # 模板引擎
mode: html
encoding: utf-8
cache: false# 禁用缓存
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #nacos服务注册

控制层实现登录验证请求,把请求发送到网关服务,网关服务在通过路由匹配到授权服务验证,获取授权成功后再去资源客户端获取数据信息。
@Controller
public class IndexController
@Autowired
private Base64Util base64Util;
@RequestMapping("/test")
public String hello(Model model)
model.addAttribute("msg", "springboot集成thymeleaf");
return "test";

@RequestMapping("/login")
public String login(Model model)
return "login";

@RequestMapping("/loginSubmit")
public String loginSubmit(Model model, String username, String password)
model.addAttribute("username", username);
OkHttpClient httpClient = new OkHttpClient();
String clientId = "oauth2-client";
String clientSecret = "oauth2-secret-8888";
String tokenUrl = "http://localhost:8101/server-api/oauth/token";
//获取token
RequestBody body = new FormBody.Builder()
.add("grant_type", "password")
.add("username", username)
.add("password",password)
.add("scope", "all")
.build();
String str = clientId + ":" + clientSecret;
String authorization = base64Util.encode(str);
Request request = new Request.Builder()
.url(tokenUrl)
.post(body)
.addHeader("Authorization", "Basic " + authorization)
.build();
String accessToken = null;
try
Response response = httpClient.newCall(request).execute();
String result = response.body().string();
ObjectMapper objectMapper = new ObjectMapper();
Map tokenMap = objectMapper.readValue(result,Map.class);
if(tokenMap.containsKey("error"))
model.addAttribute("error", tokenMap.get("error_description"));
return "login";

accessToken = tokenMap.get("access_token").toString();
Claims claims = Jwts.parser()
.setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(accessToken)
.getBody();
String userName = claims.get("user_name").toString();
model.addAttribute("username", userName);
model.addAttribute("accessToken", result);
catch (Exception e)
e.printStackTrace();

//发起客户端请求
String url = "http://localhost:8101/client-api/oauth2-client/get";
authorization = accessToken;
request = new Request.Builder()
.url(url)
.get()
.addHeader("Authorization", "bearer " + authorization)
.build();
try
Response response = httpClient.newCall(request).execute();
String result = response.body().string();
model.addAttribute("content", result);
catch (Exception e)
e.printStackTrace();

return "index";



前端登录页面
< !DOCTYPE html>
< html xmlns:th="http://www.thymeleaf.org">
< head>
< meta charset="UTF-8">
< title> 标题< /title>
< /head>
< body>
< form action="/loginSubmit" method="post">
< input type="text" placeholder="请输入账号" name="username"/>
< input type="text" placeholder="请输入密码" name="password"/>
< div style="color:red" th:text="$error" th:if="$error"/>
< button type="submit"> 登录 < /button>
< /form>
< /body>
< /html>

登录成功页面
< !DOCTYPE html>
< html xmlns:th="http://www.thymeleaf.org">
< head>
< meta charset="UTF-8">
< title> 标题< /title>
< /head>
< body>
欢迎:< span th:text="$username"> < /span> < /br>
token:< span th:text="$accessToken"> < /span> < /br>
客户端信息:< span th:text="$content"> < /span> < /br>
< /body>
< /html>

2.实现效果
使用nacos作为注册中心,先启动nacos,再启动oauth2-service, oauth2-client, oauth2-gateway, oauth2-web服务
浏览器打开??http://localhost:8848/nacos??可以查看注册的服务

打开??http://localhost:8102/login ??访问登录页面

输入账号密码admin, 123456进行登录,登录成功返回token,接口信息
【#yyds干货盘点# springboot整合Oauth2,GateWay实现网关登录授权验证】

    推荐阅读