add NoToken Feign 注解自动维护header

This commit is contained in:
冷冷 2024-06-01 12:29:24 +08:00
parent 04f01302f0
commit 993879a6c3
18 changed files with 299 additions and 257 deletions

View File

@ -27,7 +27,6 @@ import com.pig4cloud.pig.admin.api.vo.TokenVo;
import com.pig4cloud.pig.auth.support.handler.PigAuthenticationFailureEventHandler;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.RetOps;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
@ -109,7 +108,7 @@ public class PigTokenEndpoint {
@RequestParam(OAuth2ParameterNames.SCOPE) String scope,
@RequestParam(OAuth2ParameterNames.STATE) String state) {
SysOauthClientDetails clientDetails = RetOps
.of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN))
.of(clientDetailsService.getClientDetailsById(clientId))
.getData()
.orElseThrow(() -> new OAuthClientException("clientId 不合法"));

View File

@ -20,6 +20,7 @@ import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pig.common.feign.core.PigFeignInnerRequestInterceptor;
import com.pig4cloud.pig.common.feign.core.PigFeignRequestCloseInterceptor;
import com.pig4cloud.pig.common.feign.sentinel.ext.PigSentinelFeign;
import com.pig4cloud.pig.common.feign.sentinel.handle.PigUrlBlockHandler;
@ -45,33 +46,44 @@ import org.springframework.context.annotation.Scope;
@AutoConfigureBefore(SentinelFeignAutoConfiguration.class)
public class PigFeignAutoConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "feign.sentinel.enabled")
public Feign.Builder feignSentinelBuilder() {
return PigSentinelFeign.builder();
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "feign.sentinel.enabled")
public Feign.Builder feignSentinelBuilder() {
return PigSentinelFeign.builder();
}
@Bean
@ConditionalOnMissingBean
public BlockExceptionHandler blockExceptionHandler(ObjectMapper objectMapper) {
return new PigUrlBlockHandler(objectMapper);
}
@Bean
@ConditionalOnMissingBean
public BlockExceptionHandler blockExceptionHandler(ObjectMapper objectMapper) {
return new PigUrlBlockHandler(objectMapper);
}
@Bean
@ConditionalOnMissingBean
public RequestOriginParser requestOriginParser() {
return new PigHeaderRequestOriginParser();
}
@Bean
@ConditionalOnMissingBean
public RequestOriginParser requestOriginParser() {
return new PigHeaderRequestOriginParser();
}
/**
* add http connection close header
* @return
*/
@Bean
public PigFeignRequestCloseInterceptor pigFeignRequestCloseInterceptor() {
return new PigFeignRequestCloseInterceptor();
}
/**
* add http connection close header
*
* @return
*/
@Bean
public PigFeignRequestCloseInterceptor pigFeignRequestCloseInterceptor() {
return new PigFeignRequestCloseInterceptor();
}
/**
* add inner request header
*
* @return PigFeignInnerRequestInterceptor
*/
@Bean
public PigFeignInnerRequestInterceptor pigFeignInnerRequestInterceptor() {
return new PigFeignInnerRequestInterceptor();
}
}

View File

@ -0,0 +1,15 @@
package com.pig4cloud.pig.common.feign.annotation;
import java.lang.annotation.*;
/**
* 服务无token调用声明注解
* <p>
* 只有发起方没有 token 时候才需要添加此注解 @NoToken + @Inner
* <p>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoToken {
}

View File

@ -0,0 +1,34 @@
package com.pig4cloud.pig.common.feign.core;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.core.Ordered;
import java.lang.reflect.Method;
/**
* @author lengleng
* @date 2024/6/1
*/
public class PigFeignInnerRequestInterceptor implements RequestInterceptor, Ordered {
/**
* Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
*
* @param template
*/
@Override
public void apply(RequestTemplate template) {
Method method = template.methodMetadata().method();
NoToken noToken = method.getAnnotation(NoToken.class);
if (noToken != null) {
template.header(SecurityConstants.FROM, SecurityConstants.FROM_IN);
}
}
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
}

View File

@ -24,7 +24,6 @@ import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.admin.api.feign.RemoteLogService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.jackson.PigJavaTimeModule;
import com.pig4cloud.pig.common.log.config.PigLogProperties;
import lombok.RequiredArgsConstructor;
@ -45,45 +44,45 @@ import java.util.Objects;
@RequiredArgsConstructor
public class SysLogListener implements InitializingBean {
// new 一个 避免日志脱敏策略影响全局ObjectMapper
private final static ObjectMapper objectMapper = new ObjectMapper();
// new 一个 避免日志脱敏策略影响全局ObjectMapper
private final static ObjectMapper objectMapper = new ObjectMapper();
private final RemoteLogService remoteLogService;
private final RemoteLogService remoteLogService;
private final PigLogProperties logProperties;
private final PigLogProperties logProperties;
@SneakyThrows
@Async
@Order
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {
SysLogEventSource source = (SysLogEventSource) event.getSource();
SysLog sysLog = new SysLog();
BeanUtils.copyProperties(source, sysLog);
@SneakyThrows
@Async
@Order
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {
SysLogEventSource source = (SysLogEventSource) event.getSource();
SysLog sysLog = new SysLog();
BeanUtils.copyProperties(source, sysLog);
// json 格式刷参数放在异步中处理提升性能
if (Objects.nonNull(source.getBody())) {
String params = objectMapper.writeValueAsString(source.getBody());
sysLog.setParams(StrUtil.subPre(params, logProperties.getMaxLength()));
}
// json 格式刷参数放在异步中处理提升性能
if (Objects.nonNull(source.getBody())) {
String params = objectMapper.writeValueAsString(source.getBody());
sysLog.setParams(StrUtil.subPre(params, logProperties.getMaxLength()));
}
remoteLogService.saveLog(sysLog, SecurityConstants.FROM_IN);
}
remoteLogService.saveLog(sysLog);
}
@Override
public void afterPropertiesSet() {
objectMapper.addMixIn(Object.class, PropertyFilterMixIn.class);
String[] ignorableFieldNames = logProperties.getExcludeFields().toArray(new String[0]);
@Override
public void afterPropertiesSet() {
objectMapper.addMixIn(Object.class, PropertyFilterMixIn.class);
String[] ignorableFieldNames = logProperties.getExcludeFields().toArray(new String[0]);
FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
objectMapper.setFilterProvider(filters);
objectMapper.registerModule(new PigJavaTimeModule());
}
FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
objectMapper.setFilterProvider(filters);
objectMapper.registerModule(new PigJavaTimeModule());
}
@JsonFilter("filter properties by name")
class PropertyFilterMixIn {
@JsonFilter("filter properties by name")
class PropertyFilterMixIn {
}
}
}

View File

@ -57,7 +57,7 @@ public class PigAppUserDetailsServiceImpl implements PigUserDetailsService {
UserDTO userDTO = new UserDTO();
userDTO.setPhone(phone);
R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
R<UserInfo> result = remoteUserService.info(userDTO);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {

View File

@ -33,98 +33,101 @@ import java.util.Optional;
@RequiredArgsConstructor
public class PigRemoteRegisteredClientRepository implements RegisteredClientRepository {
/**
* 刷新令牌有效期默认 30
*/
private final static int refreshTokenValiditySeconds = 60 * 60 * 24 * 30;
/**
* 刷新令牌有效期默认 30
*/
private final static int refreshTokenValiditySeconds = 60 * 60 * 24 * 30;
/**
* 请求令牌有效期默认 12 小时
*/
private final static int accessTokenValiditySeconds = 60 * 60 * 12;
/**
* 请求令牌有效期默认 12 小时
*/
private final static int accessTokenValiditySeconds = 60 * 60 * 12;
private final RemoteClientDetailsService clientDetailsService;
private final RemoteClientDetailsService clientDetailsService;
/**
* Saves the registered client.
*
* <p>
* IMPORTANT: Sensitive information should be encoded externally from the
* implementation, e.g. {@link RegisteredClient#getClientSecret()}
* @param registeredClient the {@link RegisteredClient}
*/
@Override
public void save(RegisteredClient registeredClient) {
}
/**
* Saves the registered client.
*
* <p>
* IMPORTANT: Sensitive information should be encoded externally from the
* implementation, e.g. {@link RegisteredClient#getClientSecret()}
*
* @param registeredClient the {@link RegisteredClient}
*/
@Override
public void save(RegisteredClient registeredClient) {
}
/**
* Returns the registered client identified by the provided {@code id}, or
* {@code null} if not found.
* @param id the registration identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
@Override
public RegisteredClient findById(String id) {
throw new UnsupportedOperationException();
}
/**
* Returns the registered client identified by the provided {@code id}, or
* {@code null} if not found.
*
* @param id the registration identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
@Override
public RegisteredClient findById(String id) {
throw new UnsupportedOperationException();
}
/**
* Returns the registered client identified by the provided {@code clientId}, or
* {@code null} if not found.
* @param clientId the client identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
/**
* Returns the registered client identified by the provided {@code clientId}, or
* {@code null} if not found.
* @param clientId the client identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
/**
* 重写原生方法支持redis缓存
* @param clientId
* @return
*/
@Override
@SneakyThrows
@Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
public RegisteredClient findByClientId(String clientId) {
/**
* 重写原生方法支持redis缓存
*
* @param clientId
* @return
*/
@Override
@SneakyThrows
@Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
public RegisteredClient findByClientId(String clientId) {
SysOauthClientDetails clientDetails = RetOps
.of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN))
.getData()
.orElseThrow(() -> new OAuth2AuthorizationCodeRequestAuthenticationException(
new OAuth2Error("客户端查询异常,请检查数据库链接"), null));
SysOauthClientDetails clientDetails = RetOps
.of(clientDetailsService.getClientDetailsById(clientId))
.getData()
.orElseThrow(() -> new OAuth2AuthorizationCodeRequestAuthenticationException(
new OAuth2Error("客户端查询异常,请检查数据库链接"), null));
RegisteredClient.Builder builder = RegisteredClient.withId(clientDetails.getClientId())
.clientId(clientDetails.getClientId())
.clientSecret(SecurityConstants.NOOP + clientDetails.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
RegisteredClient.Builder builder = RegisteredClient.withId(clientDetails.getClientId())
.clientId(clientDetails.getClientId())
.clientSecret(SecurityConstants.NOOP + clientDetails.getClientSecret())
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
for (String authorizedGrantType : clientDetails.getAuthorizedGrantTypes()) {
builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
for (String authorizedGrantType : clientDetails.getAuthorizedGrantTypes()) {
builder.authorizationGrantType(new AuthorizationGrantType(authorizedGrantType));
}
// 回调地址
Optional.ofNullable(clientDetails.getWebServerRedirectUri())
.ifPresent(redirectUri -> Arrays.stream(redirectUri.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::redirectUri));
}
// 回调地址
Optional.ofNullable(clientDetails.getWebServerRedirectUri())
.ifPresent(redirectUri -> Arrays.stream(redirectUri.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::redirectUri));
// scope
Optional.ofNullable(clientDetails.getScope())
.ifPresent(scope -> Arrays.stream(scope.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::scope));
// scope
Optional.ofNullable(clientDetails.getScope())
.ifPresent(scope -> Arrays.stream(scope.split(StrUtil.COMMA))
.filter(StrUtil::isNotBlank)
.forEach(builder::scope));
return builder
.tokenSettings(TokenSettings.builder()
.accessTokenFormat(OAuth2TokenFormat.REFERENCE)
.accessTokenTimeToLive(Duration.ofSeconds(
Optional.ofNullable(clientDetails.getAccessTokenValidity()).orElse(accessTokenValiditySeconds)))
.refreshTokenTimeToLive(Duration.ofSeconds(Optional.ofNullable(clientDetails.getRefreshTokenValidity())
.orElse(refreshTokenValiditySeconds)))
.build())
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(!BooleanUtil.toBoolean(clientDetails.getAutoapprove()))
.build())
.build();
return builder
.tokenSettings(TokenSettings.builder()
.accessTokenFormat(OAuth2TokenFormat.REFERENCE)
.accessTokenTimeToLive(Duration.ofSeconds(
Optional.ofNullable(clientDetails.getAccessTokenValidity()).orElse(accessTokenValiditySeconds)))
.refreshTokenTimeToLive(Duration.ofSeconds(Optional.ofNullable(clientDetails.getRefreshTokenValidity())
.orElse(refreshTokenValiditySeconds)))
.build())
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(!BooleanUtil.toBoolean(clientDetails.getAutoapprove()))
.build())
.build();
}
}
}

View File

@ -20,7 +20,6 @@ import com.pig4cloud.pig.admin.api.dto.UserDTO;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
@ -40,36 +39,37 @@ import org.springframework.security.core.userdetails.UserDetails;
@RequiredArgsConstructor
public class PigUserDetailsServiceImpl implements PigUserDetailsService {
private final RemoteUserService remoteUserService;
private final RemoteUserService remoteUserService;
private final CacheManager cacheManager;
private final CacheManager cacheManager;
/**
* 用户名密码登录
* @param username 用户名
* @return
*/
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
if (cache != null && cache.get(username) != null) {
return (PigUser) cache.get(username).get();
}
/**
* 用户名密码登录
*
* @param username 用户名
* @return
*/
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
if (cache != null && cache.get(username) != null) {
return (PigUser) cache.get(username).get();
}
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {
cache.put(username, userDetails);
}
return userDetails;
}
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
R<UserInfo> result = remoteUserService.info(userDTO);
UserDetails userDetails = getUserDetails(result);
if (cache != null) {
cache.put(username, userDetails);
}
return userDetails;
}
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
}

View File

@ -38,9 +38,8 @@
</dependency>
<!--feign 注解依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
<optional>true</optional>
<groupId>com.pig4cloud</groupId>
<artifactId>pig-common-feign</artifactId>
</dependency>
<!--mybatis 依赖-->
<dependency>

View File

@ -20,13 +20,12 @@
package com.pig4cloud.pig.admin.api.feign;
import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.ServiceNameConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* @author lengleng
@ -35,15 +34,15 @@ import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(contextId = "remoteClientDetailsService", value = ServiceNameConstants.UPMS_SERVICE)
public interface RemoteClientDetailsService {
/**
* 通过clientId 查询客户端信息
* @param clientId 用户名
* @param from 调用标志
* @return R
*/
@GetMapping("/client/getClientDetailsById/{clientId}")
R<SysOauthClientDetails> getClientDetailsById(@PathVariable("clientId") String clientId,
@RequestHeader(SecurityConstants.FROM) String from);
/**
* 通过clientId 查询客户端信息 (未登录需要无token 内部调用)
*
* @param clientId 用户名
* @return R
*/
@NoToken
@GetMapping("/client/getClientDetailsById/{clientId}")
R<SysOauthClientDetails> getClientDetailsById(@PathVariable("clientId") String clientId);
}

View File

@ -20,13 +20,12 @@
package com.pig4cloud.pig.admin.api.feign;
import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.ServiceNameConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* @author lengleng
@ -36,12 +35,12 @@ import org.springframework.web.bind.annotation.RequestHeader;
public interface RemoteLogService {
/**
* 保存日志
* 保存日志 (异步多线程调用无token)
* @param sysLog 日志实体
* @param from 是否内部调用
* @return succesfalse
*/
@NoToken
@PostMapping("/log/save")
R<Boolean> saveLog(@RequestBody SysLog sysLog, @RequestHeader(SecurityConstants.FROM) String from);
R<Boolean> saveLog(@RequestBody SysLog sysLog);
}

View File

@ -1,12 +1,11 @@
package com.pig4cloud.pig.admin.api.feign;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.ServiceNameConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* @author lengleng
@ -17,13 +16,14 @@ import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(contextId = "remoteParamService", value = ServiceNameConstants.UPMS_SERVICE)
public interface RemoteParamService {
/**
* 通过key 查询参数配置
* @param key key
* @param from 声明成内部调用避免MQ 等无法调用
* @return
*/
@GetMapping("/param/publicValue/{key}")
R<String> getByKey(@PathVariable("key") String key, @RequestHeader(SecurityConstants.FROM) String from);
/**
* 通过key 查询参数配置
*
* @param key key
* @NoToken 声明成内部调用避免MQ 等无法调用
*/
@NoToken
@GetMapping("/param/publicValue/{key}")
R<String> getByKey(@PathVariable("key") String key);
}

View File

@ -18,9 +18,9 @@
package com.pig4cloud.pig.admin.api.feign;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.ServiceNameConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@ -33,34 +33,34 @@ import java.util.Map;
@FeignClient(contextId = "remoteTokenService", value = ServiceNameConstants.AUTH_SERVICE)
public interface RemoteTokenService {
/**
* 分页查询token 信息
* @param from 内部调用标志
* @param params 分页参数
* @param from 内部调用标志
* @return page
*/
@PostMapping("/token/page")
R<Page> getTokenPage(@RequestBody Map<String, Object> params, @RequestHeader(SecurityConstants.FROM) String from);
/**
* 分页查询token 信息
*
* @param params 分页参数
* @return page
*/
@NoToken
@PostMapping("/token/page")
R<Page> getTokenPage(@RequestBody Map<String, Object> params);
/**
* 删除token
* @param from 内部调用标志
* @param token token
* @param from 内部调用标志
* @return
*/
@DeleteMapping("/token/remove/{token}")
R<Boolean> removeTokenById(@PathVariable("token") String token, @RequestHeader(SecurityConstants.FROM) String from);
/**
* 删除token
*
* @param token token
* @return
*/
@NoToken
@DeleteMapping("/token/remove/{token}")
R<Boolean> removeTokenById(@PathVariable("token") String token);
/**
* 校验令牌获取用户信息
* @param token
* @param from
* @return
*/
@GetMapping("/token/query-token")
R<Map<String, Object>> queryToken(@RequestParam("token") String token,
@RequestHeader(SecurityConstants.FROM) String from);
/**
* 校验令牌获取用户信息
*
* @param token
* @return
*/
@NoToken
@GetMapping("/token/query-token")
R<Map<String, Object>> queryToken(@RequestParam("token") String token);
}

View File

@ -21,15 +21,12 @@ package com.pig4cloud.pig.admin.api.feign;
import com.pig4cloud.pig.admin.api.dto.UserDTO;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.ServiceNameConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* @author lengleng
@ -38,22 +35,15 @@ import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.UPMS_SERVICE)
public interface RemoteUserService {
/**
* 通过用户名查询用户角色信息
* @param user 用户查询对象
* @param from 调用标志
* @return R
*/
@GetMapping("/user/info/query")
R<UserInfo> info(@SpringQueryMap UserDTO user, @RequestHeader(SecurityConstants.FROM) String from);
/**
* 锁定用户
* @param username 用户名
* @param from 调用标识
* @return
*/
@PutMapping("/user/lock/{username}")
R<Boolean> lockUser(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM) String from);
/**
* (未登录状态调用需要加 @NoToken)
* 通过用户名查询用户角色信息
*
* @param user 用户查询对象
* @return R
*/
@NoToken
@GetMapping("/user/info/query")
R<UserInfo> info(@SpringQueryMap UserDTO user);
}

View File

@ -3,7 +3,6 @@ package com.pig4cloud.pig.admin.api.util;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.admin.api.feign.RemoteParamService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import lombok.experimental.UtilityClass;
@ -44,7 +43,7 @@ public class ParamResolver {
RemoteParamService remoteParamService = SpringContextHolder.getBean(RemoteParamService.class);
String result = remoteParamService.getByKey(key, SecurityConstants.FROM_IN).getData();
String result = remoteParamService.getByKey(key).getData();
if (StrUtil.isNotBlank(result)) {
return Convert.convert(clazz, result);

View File

@ -18,7 +18,6 @@
package com.pig4cloud.pig.admin.controller;
import com.pig4cloud.pig.admin.api.feign.RemoteTokenService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
@ -53,7 +52,7 @@ public class SysTokenController {
*/
@RequestMapping("/page")
public R getTokenPage(@RequestBody Map<String, Object> params) {
return remoteTokenService.getTokenPage(params, SecurityConstants.FROM_IN);
return remoteTokenService.getTokenPage(params);
}
/**
@ -66,7 +65,7 @@ public class SysTokenController {
@PreAuthorize("@pms.hasPermission('sys_token_del')")
public R removeById(@RequestBody String[] tokens) {
for (String token : tokens) {
remoteTokenService.removeTokenById(token, SecurityConstants.FROM_IN);
remoteTokenService.removeTokenById(token);
}
return R.ok();
}

View File

@ -202,7 +202,6 @@ public class SysUserController {
* @param username 用户名
* @return R
*/
@Inner
@PutMapping("/lock/{username}")
public R lockUser(@PathVariable String username) {
return userService.lockUser(username);

View File

@ -22,7 +22,6 @@ package com.pig4cloud.pig.admin.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@ -436,10 +435,7 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
@Override
public R checkPassword(String password) {
String username = SecurityUtils.getUser().getUsername();
SysUser condition = new SysUser();
condition.setUsername(username);
SysUser sysUser = this.getOne(new QueryWrapper<>(condition));
SysUser sysUser = baseMapper.selectById(SecurityUtils.getUser().getId());
if (!ENCODER.matches(password, sysUser.getPassword())) {
log.info("原密码错误");