春季安全。任何请求都需要授权,特殊的POST请求需要管理员角色。这该怎么做?

时间:2016-08-26 05:35:19

标签: spring rest spring-security

我想用Spring保护我的HATEOAS REST API构建。所有请求都需要授权和POST请求到" / rooms"应该需要管理员角色。我的WebSecurityConfigurerAdapter实现代码现在看起来像这样:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // Todo: Make sure that all resources need to be authenticated and POST rooms needs ADMIN role
                    .anyRequest().authenticated()
                    .antMatchers(HttpMethod.POST, "/api/v1/rooms").hasRole("ADMIN")
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }

现在所有资源只需要认证,如果我放了" anyRequest()。authenticated()" " antMatchers ..."行,但然后需要" ADMIN"角色不起作用或得到应用,反之亦然。

我如何让两件事同时发挥作用?

亲切的问候, 弗洛里安

2 个答案:

答案 0 :(得分:0)

Securityconfiguration.java

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and().authorizeRequests().antMatchers("/public/**")
                .permitAll().antMatchers("/sa/**").hasAuthority("sa")
                .antMatchers("/admin/**").hasAuthority("admin")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/index.html").and()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                .csrf().disable();    
    }

在其余的控制器中使用..

@RequestMapping("/admin/adduser")
    public void addUser(@RequestBody User user) {
        authService.addUser(user);
    }

答案 1 :(得分:0)

以下代码为我做了:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers(HttpMethod.POST, "/api/v1/rooms").hasRole("ADMIN")
                    .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }
}

感谢您回复Pankaj。