
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;@Componentpublic class AccessManager implements ReactiveAuthorizationManager { private static final AntPathMatcher antPathMatcher = new AntPathMatcher(); public static final ListDATABASE; @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操作…
希望这篇文章能帮到你!
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年05月14日 18时52分09秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Libevent 事件管理和添加事件
2025-04-05
libevent-简单的定时器
2025-04-05
libevent在windows下使用步骤详解
2025-04-05
libgdx的菜单配置,以及json文件的结构
2025-04-05
libiconv字符集转换库在C#中的使用
2025-04-05
liblognorm编译
2025-04-05
libmpg123 解码库用法
2025-04-05
Library Module上传Jcenter详解
2025-04-05
LibreOffice放映Slides时粗体字模糊的解决方案
2025-04-05
LibreOJ #6000. 「网络流 24 题」搭配飞行员
2025-04-05
LibreOJ 6277 数列分块入门 1(分块)
2025-04-05
Librosa基音跟踪-STFT
2025-04-05
libssh2编译部署详解
2025-04-05
LibTorch与MFC
2025-04-05
libtorch中python中cuda可以使用,但是是c++环境中不行
2025-04-05
LibTorch中TensorOptions的使用
2025-04-05
LibTorch之优化器
2025-04-05
LibTorch之全连接层(torch::nn::Linear)使用
2025-04-05