ServerHttpSecurity直接贴代码。
这是之前一直改用的配置,访问此路径一直是401(403)。但是把anyExchange也设置成permitAll。是可以访问了。(而且另一种情况:.pathMatchers(“/gateway/**”).authenticated()
.pathMatchers(“/ **”).permitAll()。这种也是可以了,就是反过来不行)。后来再想能不能吧后面这个anyExchange改一下,看了一下源码是有理由的。
贴代码2:
改成了这种。
accessManager代码块:
import cn.hutool.core.collection.ConcurrentHashSet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Set;
@Component
public class AccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {
private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
public static List<String> DATABASE;
@Value("#{'${gateway.whitelist}'.split(',')}")
public void setDatabase(List<String> db) {
DATABASE = db;
}
/**
* 实现权限验证判断
*/
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {
ServerWebExchange exchange = authorizationContext.getExchange();
//请求资源
String requestPath = exchange.getRequest().getURI().getPath();
// 是否直接放行
if (permitAll(requestPath)) {
return Mono.just(new AuthorizationDecision(true));
}
return authenticationMono.map(auth -> {
return new AuthorizationDecision(checkAuthorities(exchange, auth, requestPath));
}).defaultIfEmpty(new AuthorizationDecision(false));
}
/**
* 校验是否属于静态资源
* @param requestPath 请求路径
* @return
*/
private boolean permitAll(String requestPath) {
return DATABASE.stream()
.filter(r -> antPathMatcher.match(r.replace("/gateway", ""), requestPath)).findFirst().isPresent();
}
//权限校验
private boolean checkAuthorities(ServerWebExchange exchange, Authentication auth, String requestPath) {
Object principal = auth.getPrincipal();
return true;
}
}
现在就没有401,可以访问到了,看了改了anyExchange是好使的。
https://blog.csdn.net/yelvgou9995/article/details/107229699/