Spring Boot Security - Thymeleaf sec:authorize-url not worki



sec: authorization -url标签默认不支持Spring启动安全性:

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>

从示例中调整控制器:

@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中添加testcode

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

当我启动应用程序并登录时,无论我是否可以访问url,我都会看到"can see/admin"部分。角色评估本身按预期工作,url权限本身也是如此(当我尝试使用ROLE_USER访问它时,我得到了一个403)。

如果我在web安全配置中添加一个虚拟的privilegeEvaluator,它对每个请求都返回false, div将正确消失。

我错过了什么吗?这是预期的行为吗?我需要定义什么才能使authorize-url像使用xml配置安全性时那样工作?

更新:基本认证

此问题与SpringBootWebSecurityConfiguration:

中的基本身份验证及其自动配置有关。

SampleMethodSecurityApplication通过替换

改变ApplicationSecurity顺序
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)

@Order(SecurityProperties.BASIC_AUTH_ORDER + 1)
application.properties
security.basic.enabled: false

现在,authorization -url标记将按预期工作,但是您失去了http基本的自动配置。

<留下strong> security.basic。启用:true并且将ApplicationSecurity的顺序更改为高于BASIC_AUTH_ORDER将使您使用基本身份验证而不是表单登录…

Update - 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基本自动配置。我在这里发布了更多细节

使用 thymleaf -extras-springsecurity4应该可以解决这个问题

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

最新更新