Florian
Florian

Reputation: 267

Spring Security. Any request needs to be authorized and a special POST request needs an admin role. How to do this?

I want to secure my HATEOAS REST API build with Spring. All requests should need authorization and POST requests to "/rooms" should need the admin role. My WebSecurityConfigurerAdapter implementation code looks like this right now:

@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();
    }

Right now all resources only need authentication if I put the "anyRequest().authenticated()" line before the "antMatchers..." line, but then the needed "ADMIN" role doesn't work or get applied and vice versa.

How am I to get both things working at the same time?

Kind Regards, Florian

Upvotes: 1

Views: 5956

Answers (2)

Florian
Florian

Reputation: 267

The following code did it for me:

@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();
    }
}

Thank you for the response Pankaj.

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 881

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();    
    }

And in the rest controller use..

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

Upvotes: 0

Related Questions