Home > Software design >  Basic REST Authentication in Spring Boot
Basic REST Authentication in Spring Boot

Time:07-28

I am plying a little bit with Spring Boot and REST API.

I just want to apply some basic authentication and authorization im my application.

Unfortunately Postman returns 403 - Forbidden.

I'd appreciate you help. The code:

@RestController
@RequestMapping("/api")
public class UsersResource {

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable(name = "id") int userId) {
        return ResponseEntity.ok().body(new User("John Smith", userId));
    }
    
}
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("john").password("{noop}1234").authorities("STANDARD_USER")
                .and()
                .withUser("david").password("{noop}1234").authorities("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(GET, "/api/**").hasRole("STANDARD_USER")
                .and()
                .csrf().disable()
                .formLogin().disable();
    }
}

I am receiving this:enter image description here

The interesting part is when I change the rule to:

.antMatchers(GET, "/api/**").permitAll()

then I see the correct response. It seems that the pattern works.

CodePudding user response:

You're mixing roles with authorities. In Spring Security, a role is an authority that is prefixed with ROLE_.

You gave your users the authority STANDARD_USER, but since it doesn't start with ROLE_, it's not a role but only an authority.

That means that the following configuration won't work:

.antMatchers(GET, "/api/**").hasRole("STANDARD_USER")

To fix this, either give your user the ROLE_STANDARD_USER authority, or change hasRole("STANDARD_USER") to hasAuthority("STANDARD_USER").

CodePudding user response:

I changed the code:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("john").password("{noop}1234").roles("STANDARD_USER")
            .and()
            .withUser("david").password("{noop}1234").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.httpBasic()
            .and()
            .authorizeHttpRequests()
            .antMatchers(GET, "/api/**").hasRole("STANDARD_USER")
            .and()
            .authorizeHttpRequests().anyRequest().denyAll()
            .and()
            .csrf().disable()
            .formLogin().disable();
}

It works fine. Thank you.

  • Related