this is my Java Config:

@EnableWebSecurity
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .withUser("Jon")
                  .password("123456")
                  .roles("USER")
                .and()
                .withUser("Bob")
                  .password("qwer")
                  .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .authorizeRequests()

                .antMatchers("/admin/**").hasRole("ADMIN")

                .antMatchers(HttpMethod.GET,"/admin/**").access("hasRole('ADMIN')")

                .anyRequest().authenticated()
                .and()

                .httpBasic()
        ;
    }

}

As you can see, I hava to peroson

  • Jon, has role as USER
  • Bob, has roles as USER ADMIN

But, so Jon should not hava permition to visis /admin/**, then I write follow test

        ResultMatcher isUnauthorized = MockMvcResultMatchers.status()
                .is(401);

        String credential = Base64.getEncoder().encodeToString("Jon:123456".getBytes());

        MockHttpServletRequestBuilder builder =
                MockMvcRequestBuilders.get("/admin/")
                        .header("Authorization", "Basic " + credential);

        mockMvc.perform(builder)
                .andDo(MockMvcResultHandlers.print())
                .andExpect(isUnauthorized);

I expect this test return 401 unauthorized, But actually it return 200.

What is the problem?

SpringSecurityVersion is 5.1.5.RELEASE

0 Answers