Problem: when i try testing authenticate-required method(with MockUser) it's return 403 error, i missing something, a try several approach, but they does't work. I don't understand why this happening so, can someone explain?
For example i create simple application to demonstrate this.
Spring-security configuration class
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class SpringConfigure extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
configureAuthorization(http);
configureAuthentication(http);
}
private void configureAuthorization(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/**").authenticated();
}
private void configureAuthentication(HttpSecurity http) throws Exception {
AuthenticationEntryPoint authenticationEntryPoint = (request, response, e) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}
Controller class
@RestController
@RequestMapping("api/hello")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String hello(){
return "Hello";
}
}
and my test class
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class},webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {
RestTemplate restTemplate;
@Before
public void setUp(){
restTemplate = new RestTemplate();
}
@Test
@WithMockUser(username = "user")
public void helloTest() {
System.out.println(SecurityContextHolder.getContext().getAuthentication());
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8080/api/hello",String.class);
}
}
User created by @WithMockUser
Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER