首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java集成测试创建OAuth2主体

Java集成测试创建OAuth2主体
EN

Stack Overflow用户
提问于 2016-07-12 10:18:15
回答 1查看 1.6K关注 0票数 2

我一直试图为我们的Spring应用程序编写一个集成测试。我们使用oAuth2进行身份验证。

在这种情况下,Spring为我们提供了一个Principal实例,用于确定必须将哪些实体发送回客户端。在控制器中,我们有一个端点:

代码语言:javascript
复制
@RequestMapping("/bookings")
public @ResponseBody ResponseEntity<List<ThirdPartyBooking>> getBookings(Principal principal) {
    OAuth2Authentication auth = (OAuth2Authentication) principal;
    OAuth2AuthenticationDetails authDetails = (OAuthAuthenticationDetails) auth.getDetails();
    // Extract stuff from the details...
}

现在,在我们的测试中,我希望确保我们只为经过身份验证的用户发送预订。在测试代码下面可以找到:

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {ThirdPartyBookingServiceConfiguration.class})
@WebAppConfiguration
@Component
public abstract class RepositoryTestBase {
    @Resource
    private WebApplicationContext context;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void shouldOnlyReturnUserBookings() throws Exception {
        MockHttpServletResponse result = mockMvc.perform(MockMvcRequestBuilders.get("/bookings").principal(???)).andReturn().getResponse();
        // Validate the response
    }
}

如何在OAuth2Authentication中插入???

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-12 11:51:11

我使用RequestPostProcessor进行测试身份验证。只需将存根令牌添加到请求:

代码语言:javascript
复制
@Component
public class OAuthHelper {

    @Autowired
    AuthorizationServerTokenServices tokenservice;

    public RequestPostProcessor addBearerToken(final String username, String... authorities)
    {
        return mockRequest -> {
            OAuth2Request oauth2Request = new OAuth2Request( null, "client-id",
                        null, true, null, null, null, null, null );
            Authentication userauth = new TestingAuthenticationToken( username, null, authorities);
            OAuth2Authentication oauth2auth = new OAuth2Authentication(oauth2Request, userauth);
            OAuth2AccessToken token = tokenservice.createAccessToken(oauth2auth);

            mockRequest.addHeader("Authorization", "Bearer " + token.getValue());
            return mockRequest;
        };
    }
}

并在测试中使用:

代码语言:javascript
复制
accessToken = authHelper.addBearerToken( TEST_USER, TEST_ROLE );
    mockMvc.perform( get( "/cats" ).with( accessToken ) )
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38326028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档