Spring安全性:拒绝特定角色对资源的访问
我正在用Spring编程RESTWeb服务的集合,但无法为某些逻辑配置Spring安全性。 我有以下类型的资源: 无需身份验证即可访问的资源 仅对某些角色可访问的资源 某些角色无法访问的资源 我对最后一项要求有意见。我尝试了以下方法:Spring安全性:拒绝特定角色对资源的访问,spring,spring-security,roles,Spring,Spring Security,Roles,我正在用Spring编程RESTWeb服务的集合,但无法为某些逻辑配置Spring安全性。 我有以下类型的资源: 无需身份验证即可访问的资源 仅对某些角色可访问的资源 某些角色无法访问的资源 我对最后一项要求有意见。我尝试了以下方法: http .authorizeRequests() .antMatchers("/resource1").permitAll() .antMatch
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();
此代码与我需要的代码最为相似:
每个人都可以访问资源1,即使是未经身份验证的用户
只有用户和管理员角色才能访问资源2
只有角色管理员才能访问资源3
但是,问题在于资源4。。。如果用户经过身份验证,一切正常,只有没有任何角色的用户才能访问资源。。。问题是Spring允许访问非authenticated用户,因为我认为他们不属于规则用户,这是正确的
您知道如何将资源配置为某些角色无法访问,但必须经过身份验证吗?您可以使用。accessString表达式它允许指定URL由任意表达式保护
表达式=不具有角色“用户”且已验证
导致
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()")
您可以使用.accessString表达式,它允许指定URL由任意表达式保护
表达式=不具有角色“用户”且已验证
导致
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()")