文章目录
- 前言
- 一、用户服务
- 二、网关服务
- 1. 负载均衡
- 2. 服务调用
- 3. 登录拦截器
- 三、单元测试
- 1. 启动服务
- 2. 用户不存在
- 3. 正常登录
- 总结
前言
在上一章我们使用JWT简单完成了用户认证,【第16章】Spring Cloud之Gateway全局过滤器(安全认证),上一章内容已经太多了,这里单独抽一章出来做个优化,前面的全局过滤器只针对登录接口的用户名密码做了简单校验,这里我们增加网关服务对用户服务的调用,参数检验完成之后我们调用用户服务的用户是否存在接口做判断,
用户存在,则继续执行登录接口,不存在则返回错误信息。
一、用户服务
package org.example.user.controller;import org.example.common.model.Result;
import org.example.common.util.JwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** Create by zjg on 2024/7/21*/
@RestController
@RequestMapping("/user/")
public class UserController {List<String> users = List.of("admin");@RequestMapping("exist")public Boolean exist(@RequestParam("username") String username){boolean exist=false;if(users.contains(username)){exist=true;}return exist;}@RequestMapping("login")public Result<String> login(@RequestParam("username") String username, @RequestParam("password") String password){String message="用户名/密码不正确";String admin="admin";if(admin.equals(username)&&admin.equals(password)){Map<String, Object> claims=new HashMap<>();claims.put("username",username);return new Result<>(HttpStatus.OK.value(), "请求成功",JwtUtils.create(claims));}return Result.error(HttpStatus.UNAUTHORIZED.value(), message);}
}
二、网关服务
登录之前获取用户是否存在
1. 负载均衡
package org.example.gateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;/*** Create by zjg on 2024/7/21*/
@LoadBalancerClients({@LoadBalancerClient("user-service")
})
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {public static void main(String[] args) {SpringApplication.run(GatewayApplication.class, args);}
}
2. 服务调用
package org.example.gateway.client;import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;/*** Create by zjg on 2024/7/30*/
@Service
public class UserService {@Resourceprivate WebClient.Builder webClientBuilder;public Mono<Boolean> exist(String username) {return webClientBuilder.build().get().uri("http://user-service/user/exist?username=" + username).retrieve().bodyToMono(Boolean.class);}
}
3. 登录拦截器
package org.example.gateway.filter;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.common.model.Result;
import org.example.common.util.JwtUtils;
import org.example.gateway.client.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.concurrent.ExecutionException;/*** Create by zjg on 2024/7/31*/
@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {@AutowiredUserService userService;ObjectMapper objectMapper = new ObjectMapper();@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();ServerHttpResponse response = exchange.getResponse();String uri = request.getURI().getPath();if(uri.equals("/user/login")||uri.equals("/user/login/")){MultiValueMap<String, String> queryParams = request.getQueryParams();if(queryParams.containsKey("username")&&queryParams.containsKey("password")){Mono<Boolean> mono = userService.exist(queryParams.getFirst("username"));try {Boolean exist = mono.doOnSuccess((e)->{}).toFuture().get();if (Boolean.FALSE.equals(exist)) {response.setStatusCode(HttpStatus.BAD_REQUEST);Result result = Result.error(HttpStatus.BAD_REQUEST.value(), "登录失败", "用户名不存在!");return write(response, result);}} catch (InterruptedException e) {throw new RuntimeException(e);} catch (ExecutionException e) {throw new RuntimeException(e);}return chain.filter(exchange);}else {response.setStatusCode(HttpStatus.BAD_REQUEST);Result result = Result.error(HttpStatus.BAD_REQUEST.value(), "登录失败", "用户名和密码不能为空!");return write(response,result);}}HttpHeaders headers = request.getHeaders();String authorization = headers.getFirst("Authorization");if(Boolean.FALSE.equals(StringUtils.hasText(authorization))||Boolean.FALSE.equals(JwtUtils.verify(authorization.startsWith("Bearer")?authorization.substring(authorization.indexOf("Bearer")+7):authorization))){response.setStatusCode(HttpStatus.UNAUTHORIZED);Result result = Result.error(HttpStatus.UNAUTHORIZED.value(), "认证失败", "token验证失败,请重新获取token后重试!");return write(response,result);}request = exchange.getRequest().mutate().headers(httpHeaders -> httpHeaders.add("Source-Mark", "Z2F0ZXdheQ==")).build();return chain.filter(exchange.mutate().request(request).build());}public Mono<Void> write(ServerHttpResponse response, Result result) {try {response.getHeaders().setContentType(MediaType.APPLICATION_JSON);return response.writeWith(Flux.just(response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result))));} catch (JsonProcessingException e) {return response.setComplete();}}@Overridepublic int getOrder() {return -1;}
}
三、单元测试
1. 启动服务
2. 用户不存在
3. 正常登录
总结
回到顶部
到这里我们就完成了在网关服务中对其他服务的调用和处理,不要走开,后面的内容更精彩!!!