private ResultActions actions(MockHttpServletRequestBuilder requestBuilder) throws Exception { ResultActions actions = MockMvcClientHttpRequestFactory.this.mockMvc .perform(requestBuilder); List<Snippet> snippets = new ArrayList<>(); for (String field : this.fields) { snippets.add(new ResponseFieldSnippet(field)); } actions.andDo(document(this.label, preprocessResponse(prettyPrint()), snippets.toArray(new Snippet[0]))); this.fields = new ArrayList<>(); return actions; }
@Test void invalid_request() throws Exception { mockMvc.perform(get("/invalid_request")) .andDo( document("{ClassName}/{methodName}", preprocessResponse(prettyPrint())) ) .andExpect(status().isOk()); }
@Test public void getTokenUsingClientCredentialGrantWithAuthorizationHeader() throws Exception { String clientAuthorization = new String(Base64.encodeBase64("login:loginsecret".getBytes())); MockHttpServletRequestBuilder postForToken = post("/oauth/token") .accept(APPLICATION_JSON) .contentType(APPLICATION_FORM_URLENCODED) .param(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS) .param(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue()) .header("Authorization", "Basic " + clientAuthorization); Snippet requestParameters = requestParameters( grantTypeParameter.description("the type of authentication being used to obtain the token, in this case `client_credentials`"), opaqueFormatParameter ); Snippet requestHeaders = requestHeaders(headerWithName("Authorization").description("Base64 encoded client details in the format: `Basic client_id:client_secret`")); Snippet responseFields = responseFields( accessTokenFieldDescriptor, tokenTypeFieldDescriptor, expiresInFieldDescriptor, scopeFieldDescriptorWhenClientCredentialsToken, jtiFieldDescriptor ); mockMvc.perform(postForToken) .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), requestParameters, requestHeaders, responseFields)); }
@Test void test_Create_User() throws Exception { user = createScimUserObject(); mockMvc.perform( RestDocumentationRequestBuilders.post("/Users") .accept(APPLICATION_JSON) .header("Authorization", "Bearer " + scimWriteToken) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .content(JsonUtils.writeValueAsString(user)) ) .andExpect(status().isCreated()) .andDo( document("{ClassName}/{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestHeaders( headerWithName("Authorization").description("Access token with `scim.write` or `uaa.admin` scope required"), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), createFields, responseFields(createResponse) ) ); }
@Test void testCreateGoogleMfaProvider() throws Exception { MfaProvider<GoogleMfaProviderConfig> mfaProvider = getGoogleMfaProvider(); FieldDescriptor[] idempotentFields = getGoogleMfaProviderFields(); Snippet requestFields = requestFields(idempotentFields); Snippet responseFields = responseFields(getMfaProviderResponseFields(idempotentFields)); mockMvc.perform(RestDocumentationRequestBuilders.post("/mfa-providers", mfaProvider.getId()) .accept(APPLICATION_JSON) .header("Authorization", "Bearer " + adminToken) .contentType(APPLICATION_JSON) .content(serializeExcludingProperties(mfaProvider, "id", "created", "last_modified", "identityZoneId"))) .andExpect(status().isCreated()) .andDo(document("{ClassName}/{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestHeaders( MFA_AUTHORIZATION_HEADER, IDENTITY_ZONE_ID_HEADER ), requestFields, responseFields) ); }
@Test void updateClientMetadata() throws Exception { String clientId = generator.generate(); createClient(clientId); ClientMetadata updatedClientMetadata = new ClientMetadata(); updatedClientMetadata.setClientId(clientId); URL appLaunchUrl = new URL("http://changed.app.launch/url"); updatedClientMetadata.setAppLaunchUrl(appLaunchUrl); ResultActions perform = performUpdate(updatedClientMetadata); Snippet requestHeaders = requestHeaders( headerWithName("Authorization").description("Bearer token containing `clients.read`, `clients.admin` or `zones.{zone.id}.admin`"), headerWithName("X-Identity-Zone-Id").description("May include this header to administer another zone if using `zones.<zone.id>.admin` or `uaa.admin` scope against the default UAA zone.").optional() ); perform.andExpect(status().isOk()) .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), requestHeaders, responseFields )); }
@Test void createExternalGroupMapping() throws Exception { ScimGroup group = new ScimGroup(); group.setDisplayName("Group For Testing Creating External Group Mapping"); group = createGroup(mockMvc, scimWriteToken, group); Snippet requestHeader = requestHeaders( AUTHORIZATION_HEADER, IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ); Snippet requestFields = requestFields( fieldWithPath("groupId").required().description(GROUP_ID_DESC), fieldWithPath("externalGroup").required().description(EXTERNAL_GROUP_DESCRIPTION), fieldWithPath("origin").optional(LDAP).type(STRING).description(ORIGIN_DESC), fieldWithPath("meta.version").optional(0).description(VERSION_DESC), fieldWithPath("meta.created").ignored(), fieldWithPath("schemas").ignored() ); createExternalGroupMappingHelper(group) .andDo(document("{ClassName}/{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestHeader, requestFields, responseFields)); }
@Test void createServiceProvider() throws Exception { String json = mockMvc.perform(post("/saml/service-providers") .header("Authorization", "Bearer " + adminToken) .contentType(APPLICATION_JSON) .content(writeValueAsString(requestBody)) ).andExpect(status().isCreated()) .andDo(document("{ClassName}/{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestHeaders( headerWithName("Authorization").description("Bearer token containing `sps.write`"), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), requestFields, responseFields)) .andReturn().getResponse().getContentAsString(); SamlServiceProvider provider = JsonUtils.readValue(json, SamlServiceProvider.class); assertNotNull(provider.getConfig()); assertNotNull(provider.getConfig().getStaticCustomAttributes()); assertEquals(2, provider.getConfig().getStaticCustomAttributes().size()); assertEquals(staticAttributes, provider.getConfig().getStaticCustomAttributes()); }
@Test void testListMfaProviders() throws Exception{ MfaProvider<GoogleMfaProviderConfig> mfaProvider = getGoogleMfaProvider(); createMfaProviderHelper(mfaProvider); Snippet responseFields = responseFields((FieldDescriptor[]) subFields("[]", getMfaProviderResponseFields(getGoogleMfaProviderFields()))); ResultActions listMfaProviderAction = mockMvc.perform(RestDocumentationRequestBuilders.get("/mfa-providers") .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON)); listMfaProviderAction.andDo( document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), requestHeaders( MFA_AUTHORIZATION_HEADER, IDENTITY_ZONE_ID_HEADER), responseFields )); }
@Test void perform_auto_login() throws Exception { Map<String,Object> code = generate_auto_login_code(true); Snippet requestParameters = requestParameters( parameterWithName("code").required().type(STRING).description("The code generated from the POST /autologin"), parameterWithName("client_id").required().type(STRING).description("The client_id that generated the autologin code") ); mockMvc.perform(MockMvcRequestBuilders.get("/autologin") .param("code", (String)code.get("code")) .param("client_id", "admin")) .andDo(print()) .andDo( document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), requestParameters ) ) .andExpect(redirectedUrl("home")); }
@Test void passcode_request() throws Exception { ScimUserProvisioning userProvisioning = webApplicationContext.getBean(JdbcScimUserProvisioning.class); ScimUser marissa = userProvisioning.query("username eq \"marissa\" and origin eq \"uaa\"", IdentityZoneHolder.get().getId()).get(0); UaaPrincipal uaaPrincipal = new UaaPrincipal(marissa.getId(), marissa.getUserName(), marissa.getPrimaryEmail(), marissa.getOrigin(), marissa.getExternalId(), IdentityZoneHolder.get().getId()); UaaAuthentication principal = new UaaAuthentication(uaaPrincipal, Arrays.asList(UaaAuthority.fromAuthorities("uaa.user")), null); MockHttpSession session = new MockHttpSession(); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, new MockMvcUtils.MockSecurityContext(principal) ); MockHttpServletRequestBuilder get = MockMvcRequestBuilders.get("/passcode") .accept(APPLICATION_JSON_VALUE) .session(session) .header("Cookie","JSESSIONID="+session.getId()); mockMvc.perform(get) .andDo( document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), requestHeaders(headerWithName("Cookie").required().description("JSESSIONID cookie to match the server side session of the authenticated user.")) ) ) .andExpect(status().isOk()); }
@Test void testGetMfaProvider() throws Exception{ MfaProvider<GoogleMfaProviderConfig> mfaProvider = getGoogleMfaProvider(); mfaProvider = createMfaProviderHelper(mfaProvider); Snippet responseFields = responseFields(getMfaProviderResponseFields(getGoogleMfaProviderFields())); ResultActions getMFaResultAction = mockMvc.perform( RestDocumentationRequestBuilders.get("/mfa-providers/{id}", mfaProvider.getId()) .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON)); getMFaResultAction.andDo(document( "{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters(parameterWithName("id").required().description(ID_DESC)), requestHeaders( MFA_AUTHORIZATION_HEADER, IDENTITY_ZONE_ID_HEADER ), responseFields )); }
@Test void testDeleteMfaProvider() throws Exception { MfaProvider<GoogleMfaProviderConfig> mfaProvider = getGoogleMfaProvider(); mfaProvider = createMfaProviderHelper(mfaProvider); Snippet responseFields = responseFields(getMfaProviderResponseFields(getGoogleMfaProviderFields())); ResultActions getMFaResultAction = mockMvc.perform( RestDocumentationRequestBuilders.delete("/mfa-providers/{id}", mfaProvider.getId()) .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON)); getMFaResultAction.andDo(document( "{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters(parameterWithName("id").required().description(ID_DESC)), requestHeaders( MFA_AUTHORIZATION_HEADER, IDENTITY_ZONE_ID_HEADER ), responseFields )); }
@Test void deleteClient() throws Exception { ClientDetails createdClientDetails = JsonUtils.readValue(createClientHelper().andReturn().getResponse().getContentAsString(), BaseClientDetails.class); ResultActions resultActions = mockMvc.perform(delete("/oauth/clients/{client_id}", createdClientDetails.getClientId()) .header("Authorization", "Bearer " + clientAdminToken) .accept(APPLICATION_JSON)); resultActions.andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters( parameterWithName("client_id").required().description(clientIdDescription) ), requestHeaders( authorizationHeader, IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), responseFields((FieldDescriptor[]) ArrayUtils.addAll(idempotentFields, new FieldDescriptor[]{ lastModifiedField } ))) ); }
@Test void getClientMetadata() throws Exception { String clientId = generator.generate(); createClient(clientId); updateClientMetadata(clientId); String marissaToken = getUserAccessToken(clientId); MockHttpServletRequestBuilder get = get("/oauth/clients/{clientId}/meta", clientId) .header("Authorization", "Bearer " + marissaToken) .accept(APPLICATION_JSON); Snippet pathParameters = pathParameters( parameterWithName("clientId").description(CLIENT_ID_DESC) ); Snippet requestHeaders = requestHeaders( headerWithName("Authorization").description("Bearer token") ); mockMvc.perform(get).andExpect(status().isOk()) .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters, requestHeaders, responseFields )); }
@Test void getServiceProvider() throws Exception { MockHttpServletResponse response = mockMvc.perform(post("/saml/service-providers") .header("Authorization", "Bearer " + adminToken) .contentType(APPLICATION_JSON) .content(writeValueAsString(requestBody)) ).andReturn().getResponse(); SamlServiceProvider samlServiceProvider = JsonUtils.readValue(response.getContentAsString(), SamlServiceProvider.class); mockMvc.perform(get("/saml/service-providers/{id}", samlServiceProvider.getId()) .header("Authorization", "Bearer " + adminToken) ).andExpect(status().isOk()) .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters, requestHeaders( headerWithName("Authorization").description("Bearer token containing `sps.read`"), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), responseFields)); }
@Test void logout() throws Exception { Snippet requestParameters = requestParameters( parameterWithName("redirect").optional("Identity Zone redirect uri").type(STRING).description("On a successful logout redirect the user to here, provided the URL is whitelisted"), parameterWithName("client_id").optional(null).type(STRING).description("On a successful logout the client's redirect_uri configuration is used as the redirect uri whitelist. If this value is not provided, the identity zone whitelist will be used instead.") ); Snippet responseHeaders = responseHeaders(HeaderDocumentation.headerWithName("Location").description("Redirect URI")); mockMvc.perform( get("/logout.do") .param("redirect", "http://redirect.localhost") .param("client_id", "some_client_that_contains_redirect_uri_matching_request_param") ).andDo( document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), responseHeaders, requestParameters)) .andExpect(status().isFound()) .andExpect(redirectedUrl("http://redirect.localhost")); } }
@Test void deleteMfaRegistration() throws Exception { String accessToken = testClient.getClientCredentialsOAuthAccessToken("admin", "adminsecret", "uaa.admin"); String email = "tom.mugwort@example.com"; ScimUser tommy = new ScimUser(null, email, "Tom", "Mugwort"); tommy.setVerified(false); tommy.addEmail(email); tommy = userProvisioning.createUser(tommy, "pas5Word", IdentityZoneHolder.get().getId()); Snippet requestHeaders = requestHeaders(headerWithName("Authorization").description("Access token with `zones.<zoneId>.admin` or `uaa.admin` required."), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER); Snippet pathParameters = pathParameters( RequestDocumentation.parameterWithName("userId").description("Unique user identifier.") ); MockHttpServletRequestBuilder delete = RestDocumentationRequestBuilders.delete("/Users/{userId}/mfa", tommy.getId()) .header("Authorization", "Bearer " + accessToken); mockMvc.perform(delete) .andExpect(status().isOk()) .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters, requestHeaders)) ; } }
@Test void deleteServiceProvider() throws Exception { MockHttpServletResponse createdResponse = mockMvc.perform(MockMvcRequestBuilders.post("/saml/service-providers") .header("Authorization", "Bearer " + adminToken) .contentType(APPLICATION_JSON) .content(writeValueAsString(requestBody)) ).andReturn().getResponse(); SamlServiceProvider samlServiceProvider = JsonUtils.readValue(createdResponse.getContentAsString(), SamlServiceProvider.class); mockMvc.perform(delete("/saml/service-providers/{id}", samlServiceProvider.getId()) .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters, requestHeaders( headerWithName("Authorization").description("Bearer token containing `sps.write`"), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), responseFields)); }
@Test void deleteIdentityProvider() throws Exception { IdentityProvider identityProvider = JsonUtils.readValue(mockMvc.perform(post("/identity-providers") .header("Authorization", "Bearer " + adminToken) .contentType(APPLICATION_JSON) .content(JsonUtils.writeValueAsString(getSamlProvider("saml-for-delete")))) .andExpect(status().isCreated()) .andReturn().getResponse().getContentAsString(), IdentityProvider.class); ResultActions resultActions = deleteIdentityProviderHelper(identityProvider.getId()); resultActions .andDo(document("{ClassName}/{methodName}", preprocessResponse(prettyPrint()), pathParameters( parameterWithName("id").description(ID_DESC) ), requestHeaders( headerWithName("Authorization").description("Bearer token containing `zones.<zone id>.admin` or `uaa.admin` or `idps.write` (only in the same zone that you are a user of)"), IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER ), commonRequestParams, responseFields(getCommonProviderFieldsAnyType()))); }