(improvement)(auth) 增强UserStrategy的可配置性 (#1949)

This commit is contained in:
mislayming
2024-12-10 19:09:22 +08:00
committed by GitHub
parent 3db9a0dcec
commit a298c670ed
5 changed files with 38 additions and 3 deletions

View File

@@ -18,6 +18,9 @@ public class AuthenticationConfig {
@Value("${s2.authentication.include.path:/api}")
private String includePath;
@Value("${s2.authentication.strategy:http}")
private String strategy;
@Value("${s2.authentication.enable:false}")
private boolean enabled;

View File

@@ -7,6 +7,8 @@ import com.tencent.supersonic.common.pojo.User;
public interface UserStrategy {
String getStrategyName();
boolean accept(boolean isEnableAuthentication);
User findUser(HttpServletRequest request, HttpServletResponse response);

View File

@@ -10,6 +10,13 @@ import org.springframework.stereotype.Service;
@Service
public class FakeUserStrategy implements UserStrategy {
public static final String STRATEGY_NAME = "fake";
@Override
public String getStrategyName() {
return STRATEGY_NAME;
}
@Override
public boolean accept(boolean isEnableAuthentication) {
return !isEnableAuthentication;

View File

@@ -15,12 +15,18 @@ import java.util.Optional;
@Service
public class HttpHeaderUserStrategy implements UserStrategy {
public static final String STRATEGY_NAME = "http";
private final TokenService tokenService;
public HttpHeaderUserStrategy(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
public String getStrategyName() {
return STRATEGY_NAME;
}
@Override
public boolean accept(boolean isEnableAuthentication) {
return isEnableAuthentication;

View File

@@ -9,6 +9,7 @@ import lombok.Data;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Optional;
@Configuration
@Data
@@ -26,10 +27,26 @@ public class UserStrategyFactory {
@PostConstruct
public void setUserStrategy() {
boolean enabled = authenticationConfig.isEnabled();
if (!enabled) {
for (UserStrategy userStrategy : userStrategyList) {
if (userStrategy.accept(authenticationConfig.isEnabled())) {
UserHolder.setStrategy(userStrategy);
}
}
return;
}
String strategy = authenticationConfig.getStrategy();
Optional<UserStrategy> strategyOptional = userStrategyList.stream()
.filter(t -> t.accept(true) && strategy.equalsIgnoreCase(t.getStrategyName()))
.findAny();
if (strategyOptional.isPresent()) {
UserHolder.setStrategy(strategyOptional.get());
} else {
throw new IllegalStateException("strategy is not found: " + strategy);
}
}
}