【问题标题】:Java Spring MVC integration test create OAuth2 PrincipalJava Spring MVC 集成测试创建 OAuth2 Principal
【发布时间】:2016-11-14 12:39:11
【问题描述】:

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

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

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

现在在我们的测试中,我想确保我们只为经过身份验证的用户发送预订。下面是测试代码:

@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

【问题讨论】:

    标签: java spring-mvc spring-security principal spring-oauth2


    【解决方案1】:

    我使用 RequestPostProcessor 进行测试认证。只需在请求中添加 stub token

    @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;
            };
        }
    }
    

    并在测试中使用它:

    accessToken = authHelper.addBearerToken( TEST_USER, TEST_ROLE );
        mockMvc.perform( get( "/cats" ).with( accessToken ) )
    

    【讨论】:

    • 这不是我想要的。它确实有很大帮助。谢谢!
    猜你喜欢
    • 2012-02-17
    • 2018-02-08
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多