Spring 安全:拒绝特定角色访问资源
Spring security: deny access to resource to specific role
我正在使用 Spring 编写一组其余 Web 服务,但无法为某些逻辑配置 Spring 安全性。
我有这些类型的资源:
- 无需认证即可访问的资源
- 只有特定角色才能访问的资源
- 某些角色无法访问的资源
我对最后一个要求有疑问。我尝试了以下方法:
http
.authorizeRequests()
.antMatchers("/resource1").permitAll()
.antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource4").not().hasAuthority("ROLE_USER")
.anyRequest().fullyAuthenticated()
.and().requestCache().requestCache(new NullRequestCache())
.and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
.and().csrf().disable();
这段代码和我需要的最相似:
- 每个人都可以访问"resource1",甚至是未经身份验证的用户
- 只有角色 USER 和 ADMIN 可以访问资源 2
- 只有 ADMIN 角色可以访问 resource3
但是,问题出在 "resource4"...如果用户通过身份验证,一切正常(只有没有任何角色 USER 的用户才能访问资源)...问题是 Spring 允许访问 未经身份验证的用户 (因为我认为它认为他们不属于规则 USER,这是正确的)
知道如何将资源配置为某些角色无法访问,但必须经过身份验证吗?
您可以使用 .access(String expression)
它允许指定 URL 受任意表达式保护
with expression = "not( hasRole('USER') ) and isAuthenticated()"
导致
http
.authorizeRequests()
.antMatchers("/resource1").permitAll()
.antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
.antMatchers(HttpMethod.GET,"/resource4").access("not( hasRole('USER') ) and isAuthenticated()")
我正在使用 Spring 编写一组其余 Web 服务,但无法为某些逻辑配置 Spring 安全性。 我有这些类型的资源:
- 无需认证即可访问的资源
- 只有特定角色才能访问的资源
- 某些角色无法访问的资源
我对最后一个要求有疑问。我尝试了以下方法:
http
.authorizeRequests()
.antMatchers("/resource1").permitAll()
.antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource4").not().hasAuthority("ROLE_USER")
.anyRequest().fullyAuthenticated()
.and().requestCache().requestCache(new NullRequestCache())
.and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
.and().csrf().disable();
这段代码和我需要的最相似:
- 每个人都可以访问"resource1",甚至是未经身份验证的用户
- 只有角色 USER 和 ADMIN 可以访问资源 2
- 只有 ADMIN 角色可以访问 resource3
但是,问题出在 "resource4"...如果用户通过身份验证,一切正常(只有没有任何角色 USER 的用户才能访问资源)...问题是 Spring 允许访问 未经身份验证的用户 (因为我认为它认为他们不属于规则 USER,这是正确的)
知道如何将资源配置为某些角色无法访问,但必须经过身份验证吗?
您可以使用 .access(String expression)
它允许指定 URL 受任意表达式保护
with expression = "not( hasRole('USER') ) and isAuthenticated()"
导致
http
.authorizeRequests()
.antMatchers("/resource1").permitAll()
.antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
.antMatchers(HttpMethod.GET,"/resource4").access("not( hasRole('USER') ) and isAuthenticated()")