ServerHttpSecurity设置pathMatchers.permitAll失效,仍然401.
发布日期:2021-05-08 14:12:46 浏览次数:21 分类:精选文章

本文共 2398 字,大约阅读时间需要 7 分钟。

前两天接触了ServerHttpSecurity,刚刚接触没啥经验。直接从代码入手。

在之前一直使用的配置中,访问某些路径一直返回401(403)错误。但当我将anyExchange设置为permitAll后,问题得到了解决(而且另一种情况是:.pathMatchers("/gateway/**").authenticated()和.pathMatchers("/ **").permitAll(),这种配置也是可以的,但反过来不行)。后来我又考虑是否可以优化后面的anyExchange配置,通过查看源码我发现有相关的依据。

下面是优化后的代码片段:

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 {
private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
public static final List
DATABASE;
@Value("#{'${gateway.whitelist}'.split(',')}")
public void setDatabase(List
db) {
DATABASE = db;
}
@Override
public Mono
check(Mono
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));
}
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;
}
}

现在问题解决了,可以正常访问。

这篇文章参考了别人的博客:

以前没有接触过,但看了一下别人的博客还是有意思的,感谢提供优秀文章给我参考,用来实践想法。这一顿CV操作…

希望这篇文章能帮到你!

上一篇:获取服务器当前ip
下一篇:oracle19

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年05月14日 18时52分09秒