增加网关鉴权

master
DongZeLiang 2024-05-24 16:49:37 +08:00
parent a9023ae3d0
commit afbcb67d0d
7 changed files with 140 additions and 6 deletions

View File

@ -4,13 +4,12 @@ import com.muyu.cloud.auth.domain.request.UserLoginReq;
import com.muyu.cloud.auth.domain.response.TokenRes; import com.muyu.cloud.auth.domain.response.TokenRes;
import com.muyu.cloud.auth.service.AuthService; import com.muyu.cloud.auth.service.AuthService;
import com.muyu.cloud.system.domain.UserInfo; import com.muyu.cloud.system.domain.UserInfo;
import com.muyu.common.constant.JwtConstants;
import com.muyu.common.constant.TokenConstants;
import com.muyu.common.result.Result; import com.muyu.common.result.Result;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** /**
* @Author: DongZeLiang * @Author: DongZeLiang
@ -31,13 +30,25 @@ public class AuthController {
* *
*/ */
@PostMapping("/login") @PostMapping("/login")
public Result login(@RequestBody @Validated UserLoginReq userLoginReq) { public Result<TokenRes> login(@RequestBody @Validated UserLoginReq userLoginReq) {
UserInfo userLoginInfo = authService.login(userLoginReq.getUserName(), userLoginReq.getPassword()); UserInfo userLoginInfo = authService.login(userLoginReq.getUserName(), userLoginReq.getPassword());
TokenRes tokenRes = authService.genToken(userLoginInfo); TokenRes tokenRes = authService.genToken(userLoginInfo);
return Result.success(tokenRes); return Result.success(tokenRes);
} }
@GetMapping("/login/info")
public Result<UserInfo> getUserInfo(@RequestHeader(JwtConstants.USER_KEY) String userKey) {
return Result.success(
authService.loginInfo(userKey)
);
}
/** /**
* *
*/ */
@GetMapping("/login-out")
public Result<String> loginOut(@RequestHeader(JwtConstants.USER_KEY) String userKey){
authService.loginOut(userKey);
return Result.success();
}
} }

View File

@ -24,4 +24,17 @@ public interface AuthService {
* @return token * @return token
*/ */
TokenRes genToken (UserInfo userLoginInfo); TokenRes genToken (UserInfo userLoginInfo);
/**
* token
* @param userKey
* @return
*/
UserInfo loginInfo (String userKey);
/**
* 退
* @param userKey
*/
void loginOut (String userKey);
} }

View File

@ -96,4 +96,26 @@ public class AuthServiceImpl implements AuthService {
.expiresIn(TokenConstants.EXPIRATION) .expiresIn(TokenConstants.EXPIRATION)
.build(); .build();
} }
/**
* token
*
* @param userKey token
*
* @return
*/
@Override
public UserInfo loginInfo (String userKey) {
return redisService.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
}
/**
* 退
*
* @param userKey
*/
@Override
public void loginOut (String userKey) {
redisService.deleteObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
}
} }

View File

@ -22,7 +22,7 @@ import java.util.concurrent.TimeUnit;
@Component @Component
public class RedisService { public class RedisService {
@Scheduled(cron = "0/5 * * * * *") @Scheduled(cron = "0/5 * * * * ?")
public void scheduled() { public void scheduled() {
this.setCacheObject("skip", System.currentTimeMillis()); this.setCacheObject("skip", System.currentTimeMillis());
log.info("Redis心跳成功"); log.info("Redis心跳成功");

View File

@ -4,6 +4,7 @@ import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
/** /**
* @Author: DongZeLiang * @Author: DongZeLiang
@ -12,6 +13,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
* @Version: 1.0 * @Version: 1.0
*/ */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DruidDataSourceAutoConfigure.class}) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DruidDataSourceAutoConfigure.class})
@EnableScheduling
public class CloudGatewayApplication { public class CloudGatewayApplication {
public static void main (String[] args) { public static void main (String[] args) {

View File

@ -0,0 +1,84 @@
package com.muyu.filter;
import com.muyu.common.constant.JwtConstants;
import com.muyu.common.constant.TokenConstants;
import com.muyu.common.redis.service.RedisService;
import com.muyu.common.utils.JwtUtils;
import com.muyu.common.utils.StringUtils;
import com.muyu.config.IgnoreWhiteConfig;
import com.muyu.utils.GatewayUtils;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
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.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URI;
/**
* @Author: DongZeLiang
* @date: 2024/5/24
* @Description:
* @Version: 1.0
*/
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
private final IgnoreWhiteConfig ignoreWhiteConfig;
private final RedisService redisService;
@Override
public Mono<Void> filter (ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
URI uri = request.getURI();
String path = uri.getPath();
if (StringUtils.matches(path, ignoreWhiteConfig.getWhites())){
return chain.filter(exchange);
}
HttpHeaders requestHeaders = request.getHeaders();
String token = requestHeaders.getFirst(TokenConstants.TOKEN);
if (StringUtils.isEmpty(token)){
return GatewayUtils.errorResponse(exchange, "token不合法");
}
Claims claims = JwtUtils.parseToken(token);
if (claims == null){
return GatewayUtils.errorResponse(exchange, "token不合法");
}
String userKey = JwtUtils.getUserKey(claims);
if (!redisService.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)){
return GatewayUtils.errorResponse(exchange, "token已过期");
}
ServerHttpRequest.Builder mutate = request.mutate();
GatewayUtils.addHeader(mutate, JwtConstants.USER_KEY, userKey);
GatewayUtils.addHeader(mutate, JwtConstants.DETAILS_USER_ID, JwtUtils.getUserId(claims));
GatewayUtils.addHeader(mutate, JwtConstants.DETAILS_USERNAME, JwtUtils.getUserName(claims));
return chain.filter(exchange);
}
/**
* Get the order value of this object.
* <p>Higher values are interpreted as lower priority. As a consequence,
* the object with the lowest value has the highest priority (somewhat
* analogous to Servlet {@code load-on-startup} values).
* <p>Same order values will result in arbitrary sort positions for the
* affected objects.
*
* @return the order value
*
* @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE
*/
@Override
public int getOrder () {
return 0;
}
}

View File

@ -3,6 +3,7 @@ package com.muyu.cloud.system;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
/** /**
* @Author: DongZeLiang * @Author: DongZeLiang
@ -12,6 +13,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
*/ */
@SpringBootApplication @SpringBootApplication
@EnableFeignClients( basePackages = {"com.muyu.**"}) @EnableFeignClients( basePackages = {"com.muyu.**"})
@EnableScheduling
public class CloudSystemApplication { public class CloudSystemApplication {
public static void main(String[] args) { public static void main(String[] args) {