From 08a78772acaff6feaf604ad324c366c892f5bbea Mon Sep 17 00:00:00 2001 From: haoxr <1490493387@qq.com> Date: Tue, 27 Apr 2021 23:51:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:feign=E6=95=B4=E5=90=88sentinel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/youlai/mall/oms/OmsApplication.java | 4 +- .../oms/controller/admin/OrderController.java | 7 ++-- .../oms/service/impl/OrderServiceImpl.java | 11 +++--- ...ice.java => MemberAddressFeignClient.java} | 2 +- ...ignService.java => MemberFeignClient.java} | 2 +- ...FeignService.java => UserFeignClient.java} | 5 ++- .../api/fallback/UserFeignFallbackClient.java | 23 ++++++++++++ .../main/resources/META-INF/spring.factories | 2 + .../admin/controller/UserController.java | 10 +++-- .../admin/handler/UserBlockHandler.java | 16 +++++++- .../src/main/resources/bootstrap-dev.yml | 2 +- youlai-auth/pom.xml | 11 ++++++ .../java/com/youlai/auth/AuthApplication.java | 6 +-- .../config/AuthorizationServerConfig.java | 29 ++++++++------- .../auth/controller/AuthController.java | 9 ++--- .../auth/exception/AuthExceptionHandler.java | 13 +++++++ ...mClientCredentialsTokenEndpointFilter.java | 37 ------------------- .../auth/service/UserDetailsServiceImpl.java | 25 ++++++------- .../src/main/resources/bootstrap-dev.yml | 20 ++++++++++ .../java/com/youlai/common/result/Result.java | 3 +- .../web/exception/GlobalExceptionHandler.java | 2 +- 21 files changed, 144 insertions(+), 95 deletions(-) rename mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/{UmsAddressFeignService.java => MemberAddressFeignClient.java} (94%) rename mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/{UmsMemberFeignService.java => MemberFeignClient.java} (96%) rename youlai-admin/admin-api/src/main/java/com/youlai/admin/api/{UserFeignService.java => UserFeignClient.java} (70%) create mode 100644 youlai-admin/admin-api/src/main/java/com/youlai/admin/api/fallback/UserFeignFallbackClient.java create mode 100644 youlai-admin/admin-api/src/main/resources/META-INF/spring.factories delete mode 100644 youlai-auth/src/main/java/com/youlai/auth/filter/CustomClientCredentialsTokenEndpointFilter.java diff --git a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/OmsApplication.java b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/OmsApplication.java index 7b7d0cc31..254e5a633 100644 --- a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/OmsApplication.java +++ b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/OmsApplication.java @@ -2,7 +2,7 @@ package com.youlai.mall.oms; import com.youlai.mall.pms.api.app.PmsSkuFeignService; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.mall.ums.api.MemberFeignClient; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -12,7 +12,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @EnableDiscoveryClient -@EnableFeignClients(basePackageClasses = { UmsMemberFeignService.class, PmsSkuFeignService.class}) +@EnableFeignClients(basePackageClasses = { MemberFeignClient.class, PmsSkuFeignService.class}) @EnableRabbit public class OmsApplication { diff --git a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/controller/admin/OrderController.java b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/controller/admin/OrderController.java index a63c5557a..460855247 100644 --- a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/controller/admin/OrderController.java +++ b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/controller/admin/OrderController.java @@ -1,6 +1,5 @@ package com.youlai.mall.oms.controller.admin; -import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -10,7 +9,7 @@ import com.youlai.mall.oms.pojo.domain.OmsOrder; import com.youlai.mall.oms.pojo.domain.OmsOrderItem; import com.youlai.mall.oms.service.IOrderItemService; import com.youlai.mall.oms.service.IOrderService; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.mall.ums.api.MemberFeignClient; import com.youlai.mall.ums.pojo.dto.MemberDTO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; @@ -39,7 +38,7 @@ public class OrderController { private IOrderService orderService; private IOrderItemService orderItemService; - private UmsMemberFeignService memberFeignService; + private MemberFeignClient memberFeignClient; @ApiOperation("订单列表") @GetMapping @@ -70,7 +69,7 @@ public class OrderController { orderItems = Optional.ofNullable(orderItems).orElse(new ArrayList<>()); // 会员明细 - Result result = memberFeignService.getUserById(order.getMemberId()); + Result result = memberFeignClient.getUserById(order.getMemberId()); MemberDTO member = result.getData(); orderBO.setOrder(order).setOrderItems(orderItems).setMember(member); return Result.success(orderBO); diff --git a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java index 410b0694f..bb0d66eb8 100644 --- a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java +++ b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java @@ -27,11 +27,10 @@ import com.youlai.mall.oms.service.ICartService; import com.youlai.mall.oms.service.IOrderItemService; import com.youlai.mall.oms.service.IOrderService; import com.youlai.mall.pms.api.app.PmsSkuFeignService; -import com.youlai.mall.pms.pojo.domain.PmsSku; import com.youlai.mall.pms.pojo.dto.SkuDTO; import com.youlai.mall.pms.pojo.dto.SkuLockDTO; -import com.youlai.mall.ums.api.UmsAddressFeignService; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.mall.ums.api.MemberAddressFeignClient; +import com.youlai.mall.ums.api.MemberFeignClient; import com.youlai.mall.ums.pojo.domain.UmsAddress; import io.seata.spring.annotation.GlobalTransactional; import lombok.AllArgsConstructor; @@ -59,12 +58,12 @@ public class OrderServiceImpl extends ServiceImpl impleme private ICartService cartService; private PmsSkuFeignService skuFeignService; - private UmsAddressFeignService addressFeignService; + private MemberAddressFeignClient addressFeignService; private IOrderItemService orderItemService; private RabbitTemplate rabbitTemplate; private StringRedisTemplate redisTemplate; private ThreadPoolExecutor threadPoolExecutor; - private UmsMemberFeignService memberFeignService; + private MemberFeignClient memberFeignClient; private BusinessNoGenerator businessNoGenerator; @@ -233,7 +232,7 @@ public class OrderServiceImpl extends ServiceImpl impleme // 扣减余额 Long userId = RequestUtils.getUserId(); Long payAmount = order.getPayAmount(); - Result deductBalanceResult = memberFeignService.deductBalance(userId, payAmount); + Result deductBalanceResult = memberFeignClient.deductBalance(userId, payAmount); if (!Result.isSuccess(deductBalanceResult)) { throw new BizException("扣减账户余额失败"); } diff --git a/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsAddressFeignService.java b/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberAddressFeignClient.java similarity index 94% rename from mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsAddressFeignService.java rename to mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberAddressFeignClient.java index 2e969a78c..b50c74091 100644 --- a/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsAddressFeignService.java +++ b/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberAddressFeignClient.java @@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @FeignClient(name = "mall-ums",contextId = "address") -public interface UmsAddressFeignService { +public interface MemberAddressFeignClient { /** * 获取地址详情 diff --git a/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsMemberFeignService.java b/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberFeignClient.java similarity index 96% rename from mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsMemberFeignService.java rename to mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberFeignClient.java index 8f9909b73..9deb771e6 100644 --- a/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/UmsMemberFeignService.java +++ b/mall-ums/ums-api/src/main/java/com/youlai/mall/ums/api/MemberFeignClient.java @@ -8,7 +8,7 @@ import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; @FeignClient(name = "mall-ums",contextId = "member") -public interface UmsMemberFeignService { +public interface MemberFeignClient { @PostMapping("/api.app/v1/members") Result add(@RequestBody UmsMember user); diff --git a/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignService.java b/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignClient.java similarity index 70% rename from youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignService.java rename to youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignClient.java index c21222722..5c4b6dd7c 100644 --- a/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignService.java +++ b/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/UserFeignClient.java @@ -1,13 +1,14 @@ package com.youlai.admin.api; +import com.youlai.admin.api.fallback.UserFeignFallbackClient; import com.youlai.admin.pojo.dto.UserDTO; import com.youlai.common.result.Result; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -@FeignClient(value = "youlai-admin") -public interface UserFeignService { +@FeignClient(value = "youlai-admin", fallback = UserFeignFallbackClient.class) +public interface UserFeignClient { @GetMapping("/api.admin/v1/users/username/{username}") Result getUserByUsername(@PathVariable String username); diff --git a/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/fallback/UserFeignFallbackClient.java b/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/fallback/UserFeignFallbackClient.java new file mode 100644 index 000000000..440133647 --- /dev/null +++ b/youlai-admin/admin-api/src/main/java/com/youlai/admin/api/fallback/UserFeignFallbackClient.java @@ -0,0 +1,23 @@ +package com.youlai.admin.api.fallback; + +import com.youlai.admin.api.UserFeignClient; +import com.youlai.admin.pojo.dto.UserDTO; +import com.youlai.common.result.Result; +import com.youlai.common.result.ResultCode; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * @author haoxr + * @createTime 2021/4/24 21:30 + */ +@Component +@Slf4j +public class UserFeignFallbackClient implements UserFeignClient { + + @Override + public Result getUserByUsername(String username) { + log.error("Feign远程调用服务发生故障,获取用户信息失败降级"); + return Result.failed(ResultCode.DEGRADATION); + } +} diff --git a/youlai-admin/admin-api/src/main/resources/META-INF/spring.factories b/youlai-admin/admin-api/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..48f9273a9 --- /dev/null +++ b/youlai-admin/admin-api/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.youlai.admin.api.fallback.UserFeignFallbackClient diff --git a/youlai-admin/admin-boot/src/main/java/com/youlai/admin/controller/UserController.java b/youlai-admin/admin-boot/src/main/java/com/youlai/admin/controller/UserController.java index c0cfc463f..01ed0419b 100644 --- a/youlai-admin/admin-boot/src/main/java/com/youlai/admin/controller/UserController.java +++ b/youlai-admin/admin-boot/src/main/java/com/youlai/admin/controller/UserController.java @@ -1,7 +1,6 @@ package com.youlai.admin.controller; import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.collection.CollectionUtil; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; @@ -146,6 +145,8 @@ public class UserController extends BaseController { public Result getUserByUsername( @PathVariable String username ) { + log.info("进入getUserByUsername方法"); + int i = 1 / 0; SysUser user = iSysUserService.getOne(new LambdaQueryWrapper() .eq(SysUser::getUsername, username)); @@ -169,10 +170,13 @@ public class UserController extends BaseController { @ApiOperation(value = "获取当前登陆的用户信息") - @SentinelResource(value = "getCurrentUser",blockHandlerClass = UserBlockHandler.class,blockHandler = - "handleGetCurrentUserBlock") + @SentinelResource(value = "getCurrentUser", + blockHandlerClass = UserBlockHandler.class, blockHandler = "handleGetCurrentUserBlock" + ) @GetMapping("/me") public Result getCurrentUser() { + log.info("获取当前登陆的用户信息 begin"); + UserVO userVO = new UserVO(); // 用户基本信息 diff --git a/youlai-admin/admin-boot/src/main/java/com/youlai/admin/handler/UserBlockHandler.java b/youlai-admin/admin-boot/src/main/java/com/youlai/admin/handler/UserBlockHandler.java index a2e3667f2..8fe514d75 100644 --- a/youlai-admin/admin-boot/src/main/java/com/youlai/admin/handler/UserBlockHandler.java +++ b/youlai-admin/admin-boot/src/main/java/com/youlai/admin/handler/UserBlockHandler.java @@ -3,14 +3,28 @@ package com.youlai.admin.handler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.youlai.admin.pojo.vo.UserVO; import com.youlai.common.result.Result; +import lombok.extern.slf4j.Slf4j; /** + * 用户接口降级逻辑 * @author haoxr - * @description TODO * @createTime 2021/4/23 23:30 */ +@Slf4j public class UserBlockHandler { + + /** + * 获取当前登录用户信息的熔断降级处理 + * @param blockException + * @return + */ public static Result handleGetCurrentUserBlock(BlockException blockException) { return Result.success(new UserVO()); } + + + public static Result handleGetUserByUsernameBlock(String username,BlockException blockException){ + log.info("降级了:{}",username); + return Result.failed("降级 了"); + } } diff --git a/youlai-admin/admin-boot/src/main/resources/bootstrap-dev.yml b/youlai-admin/admin-boot/src/main/resources/bootstrap-dev.yml index 43f799d1e..6e64965d4 100644 --- a/youlai-admin/admin-boot/src/main/resources/bootstrap-dev.yml +++ b/youlai-admin/admin-boot/src/main/resources/bootstrap-dev.yml @@ -12,7 +12,7 @@ spring: server-addr: ${spring.cloud.nacos.discovery.server-addr} file-extension: yaml sentinel: - enabled: false + enabled: true eager: true # 取消控制台懒加载,项目启动即连接Sentinel transport: client-ip: localhost diff --git a/youlai-auth/pom.xml b/youlai-auth/pom.xml index c0c08aa5d..e95f362f5 100644 --- a/youlai-auth/pom.xml +++ b/youlai-auth/pom.xml @@ -63,6 +63,17 @@ spring-security-oauth2-jose + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + com.alibaba.csp + sentinel-datasource-nacos + + com.youlai ums-api diff --git a/youlai-auth/src/main/java/com/youlai/auth/AuthApplication.java b/youlai-auth/src/main/java/com/youlai/auth/AuthApplication.java index 497864120..4eaeca91c 100644 --- a/youlai-auth/src/main/java/com/youlai/auth/AuthApplication.java +++ b/youlai-auth/src/main/java/com/youlai/auth/AuthApplication.java @@ -1,13 +1,13 @@ package com.youlai.auth; -import com.youlai.admin.api.UserFeignService; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.admin.api.UserFeignClient; +import com.youlai.mall.ums.api.MemberFeignClient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; -@EnableFeignClients(basePackageClasses = {UserFeignService.class, UmsMemberFeignService.class}) +@EnableFeignClients(basePackageClasses = {UserFeignClient.class, MemberFeignClient.class}) @SpringBootApplication @EnableDiscoveryClient public class AuthApplication { diff --git a/youlai-auth/src/main/java/com/youlai/auth/config/AuthorizationServerConfig.java b/youlai-auth/src/main/java/com/youlai/auth/config/AuthorizationServerConfig.java index 5afc9362f..eb6d5394d 100644 --- a/youlai-auth/src/main/java/com/youlai/auth/config/AuthorizationServerConfig.java +++ b/youlai-auth/src/main/java/com/youlai/auth/config/AuthorizationServerConfig.java @@ -3,7 +3,6 @@ package com.youlai.auth.config; import cn.hutool.http.HttpStatus; import cn.hutool.json.JSONUtil; import com.youlai.auth.domain.User; -import com.youlai.auth.filter.CustomClientCredentialsTokenEndpointFilter; import com.youlai.auth.service.JdbcClientDetailsServiceImpl; import com.youlai.auth.service.UserDetailsServiceImpl; import com.youlai.common.constant.AuthConstants; @@ -17,6 +16,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; @@ -47,6 +48,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap private DataSource dataSource; private AuthenticationManager authenticationManager; private UserDetailsServiceImpl userDetailsService; + private PasswordEncoder passwordEncoder; /** * 配置客户端详情(数据库) @@ -86,20 +88,13 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap @Override public void configure(AuthorizationServerSecurityConfigurer security) { - /*security.allowFormAuthenticationForClients();*/ - CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security); - endpointFilter.afterPropertiesSet(); - endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint()); - security.addTokenEndpointAuthenticationFilter(endpointFilter); - - security.authenticationEntryPoint(authenticationEntryPoint()) - .tokenKeyAccess("isAuthenticated()") - .checkTokenAccess("permitAll()"); + security.allowFormAuthenticationForClients(); } /** * 自定义认证异常响应数据 + * * @return */ @Bean @@ -133,8 +128,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap public KeyPair keyPair() { KeyStoreKeyFactory factory = new KeyStoreKeyFactory( new ClassPathResource("youlai.jks"), "123456".toCharArray()); - KeyPair keyPair = factory.getKeyPair( - "youlai", "123456".toCharArray()); + KeyPair keyPair = factory.getKeyPair("youlai", "123456".toCharArray()); return keyPair; } @@ -148,9 +142,18 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap User user = (User) authentication.getUserAuthentication().getPrincipal(); map.put(AuthConstants.USER_ID_KEY, user.getId()); map.put(AuthConstants.CLIENT_ID_KEY, user.getClientId()); - map.put(AuthConstants.USER_NAME_KEY,user.getUsername()); + map.put(AuthConstants.USER_NAME_KEY, user.getUsername()); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map); return accessToken; }; } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setHideUserNotFoundExceptions(false); + provider.setUserDetailsService(userDetailsService); + provider.setPasswordEncoder(passwordEncoder); + return provider; + } } diff --git a/youlai-auth/src/main/java/com/youlai/auth/controller/AuthController.java b/youlai-auth/src/main/java/com/youlai/auth/controller/AuthController.java index 40747beab..092945408 100644 --- a/youlai-auth/src/main/java/com/youlai/auth/controller/AuthController.java +++ b/youlai-auth/src/main/java/com/youlai/auth/controller/AuthController.java @@ -10,7 +10,7 @@ import com.youlai.common.result.Result; import com.youlai.common.result.ResultCode; import com.youlai.common.web.exception.BizException; import com.youlai.common.web.util.RequestUtils; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.mall.ums.api.MemberFeignClient; import com.youlai.mall.ums.pojo.domain.UmsMember; import com.youlai.mall.ums.pojo.dto.AuthMemberDTO; import io.swagger.annotations.Api; @@ -20,7 +20,6 @@ import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import me.chanjar.weixin.common.error.WxErrorException; import org.apache.logging.log4j.util.Strings; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.common.OAuth2AccessToken; @@ -86,7 +85,7 @@ public class AuthController { private WxMaService wxService; - private UmsMemberFeignService memberFeignService; + private MemberFeignClient memberFeignClient; private PasswordEncoder passwordEncoder; @SneakyThrows @@ -104,7 +103,7 @@ public class AuthController { String openid = session.getOpenid(); String sessionKey = session.getSessionKey(); - Result result = memberFeignService.getUserByOpenid(openid); + Result result = memberFeignClient.getUserByOpenid(openid); if (ResultCode.USER_NOT_EXIST.getCode().equals(result.getCode())) { // 微信授权登录 会员信息不存在时 注册会员 String encryptedData = parameters.get("encryptedData"); @@ -123,7 +122,7 @@ public class AuthController { .setPassword(passwordEncoder.encode(openid).replace(AuthConstants.BCRYPT, Strings.EMPTY)) // 加密密码移除前缀加密方式 {bcrypt} .setStatus(GlobalConstants.STATUS_NORMAL_VALUE); - Result res = memberFeignService.add(user); + Result res = memberFeignClient.add(user); if (!ResultCode.SUCCESS.getCode().equals(res.getCode())) { throw new BizException("注册会员失败"); } diff --git a/youlai-auth/src/main/java/com/youlai/auth/exception/AuthExceptionHandler.java b/youlai-auth/src/main/java/com/youlai/auth/exception/AuthExceptionHandler.java index dd10edd9d..1e9d03817 100644 --- a/youlai-auth/src/main/java/com/youlai/auth/exception/AuthExceptionHandler.java +++ b/youlai-auth/src/main/java/com/youlai/auth/exception/AuthExceptionHandler.java @@ -4,6 +4,7 @@ import com.youlai.common.result.Result; import com.youlai.common.result.ResultCode; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.InternalAuthenticationServiceException; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @@ -12,6 +13,18 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; @Slf4j public class AuthExceptionHandler { + /** + * 用户不存在 + * + * @param e + * @return + */ + @ExceptionHandler(UsernameNotFoundException.class) + public Result handleUsernameNotFoundException(UsernameNotFoundException e) { + return Result.failed(ResultCode.USER_NOT_EXIST); + } + + /** * 用户名和密码异常 * diff --git a/youlai-auth/src/main/java/com/youlai/auth/filter/CustomClientCredentialsTokenEndpointFilter.java b/youlai-auth/src/main/java/com/youlai/auth/filter/CustomClientCredentialsTokenEndpointFilter.java deleted file mode 100644 index a6f786ffa..000000000 --- a/youlai-auth/src/main/java/com/youlai/auth/filter/CustomClientCredentialsTokenEndpointFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.youlai.auth.filter; - -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter; -import org.springframework.security.web.AuthenticationEntryPoint; - -/** - * 重写filter实现客户端自定义异常处理 - */ -public class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter { - - private AuthorizationServerSecurityConfigurer configurer; - private AuthenticationEntryPoint authenticationEntryPoint; - - public CustomClientCredentialsTokenEndpointFilter(AuthorizationServerSecurityConfigurer configurer) { - this.configurer = configurer; - } - - @Override - public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) { - super.setAuthenticationEntryPoint(null); - this.authenticationEntryPoint = authenticationEntryPoint; - } - - @Override - protected AuthenticationManager getAuthenticationManager() { - return configurer.and().getSharedObject(AuthenticationManager.class); - } - - @Override - public void afterPropertiesSet() { - setAuthenticationFailureHandler((request, response, e) -> authenticationEntryPoint.commence(request, response, e)); - setAuthenticationSuccessHandler((request, response, authentication) -> { - }); - } -} diff --git a/youlai-auth/src/main/java/com/youlai/auth/service/UserDetailsServiceImpl.java b/youlai-auth/src/main/java/com/youlai/auth/service/UserDetailsServiceImpl.java index b7b7b44c8..56da27b37 100644 --- a/youlai-auth/src/main/java/com/youlai/auth/service/UserDetailsServiceImpl.java +++ b/youlai-auth/src/main/java/com/youlai/auth/service/UserDetailsServiceImpl.java @@ -1,16 +1,16 @@ package com.youlai.auth.service; -import com.youlai.admin.api.UserFeignService; +import com.youlai.admin.api.UserFeignClient; import com.youlai.admin.pojo.dto.UserDTO; import com.youlai.auth.domain.User; import com.youlai.common.constant.AuthConstants; import com.youlai.common.result.Result; import com.youlai.common.result.ResultCode; -import com.youlai.common.web.exception.BizException; import com.youlai.common.web.util.RequestUtils; -import com.youlai.mall.ums.api.UmsMemberFeignService; +import com.youlai.mall.ums.api.MemberFeignClient; import com.youlai.mall.ums.pojo.dto.AuthMemberDTO; import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; @@ -25,10 +25,11 @@ import org.springframework.stereotype.Service; */ @Service @AllArgsConstructor +@Slf4j public class UserDetailsServiceImpl implements UserDetailsService { - private UserFeignService userFeignService; - private UmsMemberFeignService memberFeignService; + private UserFeignClient userFeignClient; + private MemberFeignClient memberFeignClient; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { @@ -38,28 +39,24 @@ public class UserDetailsServiceImpl implements UserDetailsService { Result result; switch (clientId) { case AuthConstants.ADMIN_CLIENT_ID: // 后台用户 - result = userFeignService.getUserByUsername(username); + result = userFeignClient.getUserByUsername(username); + log.info("获取用户信息:{}",result.toString()); if (ResultCode.SUCCESS.getCode().equals(result.getCode())) { UserDTO userDTO = (UserDTO) result.getData(); user = new User(userDTO); - } else { - throw new BizException(result.getMsg()); } break; case AuthConstants.WEAPP_CLIENT_ID: // 小程序会员 - result = memberFeignService.getUserByOpenid(username); + result = memberFeignClient.getUserByOpenid(username); if (ResultCode.SUCCESS.getCode().equals(result.getCode())) { AuthMemberDTO authMemberDTO = (AuthMemberDTO) result.getData(); user = new User(authMemberDTO); - } else { - throw new BizException(result.getMsg()); } break; } - if (user == null) { + if (user == null || user.getId() == null) { throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg()); - } - if (!user.isEnabled()) { + } else if (!user.isEnabled()) { throw new DisabledException("该账户已被禁用!"); } else if (!user.isAccountNonLocked()) { throw new LockedException("该账号已被锁定!"); diff --git a/youlai-auth/src/main/resources/bootstrap-dev.yml b/youlai-auth/src/main/resources/bootstrap-dev.yml index aa0bd64fe..132578572 100644 --- a/youlai-auth/src/main/resources/bootstrap-dev.yml +++ b/youlai-auth/src/main/resources/bootstrap-dev.yml @@ -13,3 +13,23 @@ spring: server-addr: ${spring.cloud.nacos.discovery.server-addr} file-extension: yaml group: DEFAULT_GROUP + sentinel: + enabled: true + eager: true # 取消控制台懒加载,项目启动即连接Sentinel + transport: + client-ip: localhost + dashboard: localhost:8080 + datasource: + # 降级规则 + degrade: + nacos: + server-addr: ${spring.cloud.nacos.discovery.server-addr} + dataId: ${spring.application.name}-degrade-rules + groupId: SENTINEL_GROUP + data-type: json + rule-type: degrade + +# 开启feign对sentinel的支持 +feign: + sentinel: + enabled: true diff --git a/youlai-common/common-core/src/main/java/com/youlai/common/result/Result.java b/youlai-common/common-core/src/main/java/com/youlai/common/result/Result.java index 8b6337574..0c94bbdbe 100644 --- a/youlai-common/common-core/src/main/java/com/youlai/common/result/Result.java +++ b/youlai-common/common-core/src/main/java/com/youlai/common/result/Result.java @@ -10,6 +10,8 @@ import java.io.Serializable; * @date 2020-06-23 **/ @Data +// 忽略null值 +@JsonInclude(JsonInclude.Include.NON_NULL) public class Result implements Serializable { private String code; @@ -18,7 +20,6 @@ public class Result implements Serializable { private String msg; - @JsonInclude(JsonInclude.Include.NON_NULL) private Integer total; public static Result success() { diff --git a/youlai-common/common-web/src/main/java/com/youlai/common/web/exception/GlobalExceptionHandler.java b/youlai-common/common-web/src/main/java/com/youlai/common/web/exception/GlobalExceptionHandler.java index 9ce3167c5..50dc5897e 100644 --- a/youlai-common/common-web/src/main/java/com/youlai/common/web/exception/GlobalExceptionHandler.java +++ b/youlai-common/common-web/src/main/java/com/youlai/common/web/exception/GlobalExceptionHandler.java @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; * @author hxrui * @date 2020-02-25 13:54 **/ -//@RestControllerAdvice +// @RestControllerAdvice @Slf4j public class GlobalExceptionHandler {