如何仅使用Spring Security允​​许匿名用户访问特定功能

时间:2018-07-02 04:14:34

标签: spring spring-boot spring-security

我在项目中使用Spring Security。 我有一个条件,匿名用户应该能够从数据库中读取,而只有授权用户才能添加/更新/删除。 我们如何在security-config中提及这种情况?

.antMatchers("/user/**").permitAll()

所有许可都需要经过身份验证,但我甚至希望没有经过身份验证的用户都可以通过GET方法访问。

@RequestMapping("/user")
@PreAuthorize("hasAuthority('USER')")
public List<UserAll> getAll() {

    return userService.getAll();
}

在这里我该如何提及匿名用户也应该访问此功能?

1 个答案:

答案 0 :(得分:2)

在我的WebSecurityConfig类中,我使用以下代码:

    .authorizeRequests()
            .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**")
                .permitAll()
            .antMatchers("/secure/rest/**")
                .authenticated()
            .antMatchers("/register**")
                .anonymous()
            .antMatchers("/login**")
                .anonymous()
            .and();

这是什么,它仅允许未经身份验证的用户使用注册和登录端点。它仅允许经过身份验证的用户访问其他端点(以/ secure / rest开头的端点)。 它还允许经过身份验证的用户和未经身份验证的用户都使用我的Swagger端点。

permitAll不需要对用户进行身份验证。它允许所有请求通过。

作为旁注,我建议每个环境具有不同的安全性配置。我不建议在产品环境中向所有人公开Swagger端点。上面的配置适用于我的较低级开发环境。