gpt4 book ai didi

Spring Boot 安全 - Thymeleaf 秒 :authorize-url not working

转载 作者:行者123 更新时间:2023-12-02 11:22:41 25 4
gpt4 key购买 nike

默认情况下,sec:authorize-url 标签不适用于 Spring boot 安全性:

git clone https://github.com/spring-projects/spring-boot

项目 spring-boot-sample-web-method-security:

添加依赖

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity3</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>

根据示例调整 Controller :

@RequestMapping("/")
public String home(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}

@RequestMapping("/admin/foo")
public String home2(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}

将 URL 匹配添加到应用程序安全性:

http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
...

在 home.html 中添加测试代码

<div sec:authorize="hasRole('ROLE_ADMIN')">
has role admin
</div>
<div sec:authorize-url="/admin/foo">
can see /admin
</div>

当我启动应用程序并登录时,无论我是否可以实际访问该网址,我总是会看到“可以看到/admin”部分。角色评估本身按预期工作,url 权限本身也按预期工作(当我尝试使用 ROLE_USER 访问它时,我收到 403)。

如果我向 Web 安全配置添加一个虚拟特权评估器,该配置仅对每个请求返回 false,则 div 将正确消失。

我在这里遗漏了什么吗?这是预期的行为吗?我需要定义什么才能使authorize-url 按照使用 xml 配置安全性时的方式工作?

更新:基本身份验证

此问题与 SpringBootWebSecurityConfiguration 中的基本身份验证及其自动配置有关:

SampleMethodSecurityApplication 中,通过替换以下内容来更改 ApplicationSecurity 顺序:

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)

@Order(SecurityProperties.BASIC_AUTH_ORDER + 1)

并在 Spring Boot 中停用基本 application.properties

security.basic.enabled: false

现在,authorize-url 标签将按预期工作,但当然您已经失去了 http 基本自动配置。

保留 security.basic.enabled: true 并将 ApplicationSecurity 的顺序更改为高于 BASIC_AUTH_ORDER 将使您使用基本身份验证而不是表单登录...

更新 - PrivilegeEvaluator

我找到了以下解决方法。只需在 SecurityConfig 中手动注册安全拦截器即可:

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Override
public void configure(final WebSecurity web) throws Exception {
final HttpSecurity http = getHttp();
web.postBuildAction(new Runnable() {
@Override
public void run() {
web.securityInterceptor(http.getSharedObject(FilterSecurityInterceptor.class));
}
});
}

它允许您使用推荐的 ACCESS_OVERRIDE_ORDER 和 http 基本自动配置。我已经发布了更多详细信息here任何解释为什么它有效的解释都是值得赞赏的。

最佳答案

使用thymeleaf-extras-springsecurity4应该可以解决问题

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

关于Spring Boot 安全 - Thymeleaf 秒 :authorize-url not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23686022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com