Spring TestRestTemplate身份验证

时间:2017-08-06 10:30:18

标签: authentication testing spring-boot spring-rest

我正在尝试构建Spring Boot测试以测试其余的API,以便我可以从请求中获取Principal并使用它来识别用户。 服务器返回

  

{ “时间戳”:1502014507361, “状态”:403, “错误”: “禁止”, “消息”:“访问   被拒绝”, “路径”: “/你好”}

我在这里缺少什么?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestTemplateTest {

    @Autowired
    TestRestTemplate testRestTemplate;

    @Test
    public void testit() {

        testRestTemplate.withBasicAuth("user", "password");
        String responsePayload = testRestTemplate.getForObject("/hello", String.class);
    }



@RestController
public class GreetingController {

    @RequestMapping("/hello")
    public String heipat(Principal principal) {
        String string = "hello there";
        return string;
    }



    @Configuration
    @EnableWebSecurity
    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequests().anyRequest().hasRole("USER");
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
            authenticationManagerBuilder.inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER");
        }

    }

1 个答案:

答案 0 :(得分:0)

您需要先进行身份验证。比如请求/login API。 此外,您需要通过执行以下操作使每个人都可以访问登录API:

http.csrf().disable().authorizeRequests()
    .antMatchers("/login").permitAll()

当您加入WebSecurityConfig时,您将拥有基本的usernamerAndPassowrd身份验证。