Spring Security / rolesAllowed / antMatchers

时间:2013-12-11 20:39:10

标签: spring spring-security spring-data-rest

我正在使用Spring Data REST,我的存储库中有一个find方法:

public List<Contact> findByLastNameOrderByLastNameAsc(@Param("lastName") String lastName);

我正在尝试为方法添加安全性,但没有运气。在我的数据库中,我有一个用户角色为'ROLE_USER'。当服务启动时,登录表单出现,我可以使用数据库中的凭据登录。

这是我的网络安全配置:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery("select username,identification,enabled from users where username = ?");


  }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .antMatchers("/contacts/findByLastNameOrderByLastNameAsc").hasRole("ADMIN")
    .antMatchers("/contacts/**").fullyAuthenticated()
    .antMatchers("/contacts/**").hasRole("USER")
    .anyRequest().authenticated()

    .and()
     .formLogin();
}

当我尝试在我的存储库中调用服务时,我没有看到任何身份验证错误。使用我的浏览器,即使数据库中的用户没有“ADMIN”角色,URL也会正常显示。

我尝试将'RolesAllowed'添加到我的存储库中的方法,但没有运气:

@RolesAllowed(value = { "ADMIN" })
public List<Contact> findByLastNameOrderByLastNameAsc(@Param("lastName") String lastName);

我是否正在为Spring Data提供的REST API正确添加安全性?关于如何使其发挥作用的想法?

感谢

1 个答案:

答案 0 :(得分:5)

FWIW:我忘了添加jsr250支持。所以,我添加了这个配置:

@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {

}

现在RolesAllowed注释工作正常。

相关问题