org.springframework.http.HttpMethod Java Examples
The following examples show how to use
org.springframework.http.HttpMethod.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestSpringMVCObjectParamType.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testMultiLayerObjectParam_rt() { MultiLayerObjectParam request = new MultiLayerObjectParam("sss-1", new Date(), new MultiLayerObjectParam2("sss-2", 12.12, FlattenObjectRequest.createFlattenObjectRequest())); ResponseEntity<MultiLayerObjectParam> responseEntity = consumers.getSCBRestTemplate() .exchange("/testMultiLayerObjectParam", HttpMethod.PUT, new HttpEntity<>(request), MultiLayerObjectParam.class); assertEquals(request, responseEntity.getBody()); assertEquals(200, responseEntity.getStatusCodeValue()); responseEntity = consumers.getSCBRestTemplate() .exchange("/testMultiLayerObjectParam", HttpMethod.PUT, new HttpEntity<>(null), MultiLayerObjectParam.class); // Highway will not give null return value Assert.assertTrue(responseEntity.getBody() == null || responseEntity.getBody().getString() == null); assertEquals(200, responseEntity.getStatusCodeValue()); }
Example #2
Source File: DefaultCorsProcessorTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void preflightRequestCredentialsWithOriginWildcard() throws Exception { this.request.setMethod(HttpMethod.OPTIONS.name()); this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1"); this.conf.addAllowedOrigin("https://domain1.com"); this.conf.addAllowedOrigin("*"); this.conf.addAllowedOrigin("http://domain3.com"); this.conf.addAllowedHeader("Header1"); this.conf.setAllowCredentials(true); this.processor.processRequest(this.conf, this.request, this.response); assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); }
Example #3
Source File: ResourceWebScriptDelete.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 6 votes |
@Override public Void execute(final ResourceWithMetadata resource, final Params params, final WebScriptResponse res, boolean isReadOnly) { final ResourceOperation operation = resource.getMetaData().getOperation(HttpMethod.DELETE); final WithResponse callBack = new WithResponse(operation.getSuccessStatus(), DEFAULT_JSON_CONTENT,CACHE_NEVER); // MNT-20308 - allow write transactions for authentication api RetryingTransactionHelper transHelper = getTransactionHelper(resource.getMetaData().getApi().getName()); transHelper.doInTransaction( new RetryingTransactionCallback<Void>() { @Override public Void execute() throws Throwable { executeAction(resource, params, callBack); //ignore return result return null; } }, false, true); setResponse(res,callBack); return null; }
Example #4
Source File: DefaultContainerImageMetadataResolverTest.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
private void mockBlogRestTemplateCall(String jsonResponse, String registryHost, String registryPort, String repository, String digest) { UriComponents blobUriComponents = UriComponentsBuilder.newInstance() .scheme("https") .host(registryHost) .port(StringUtils.hasText(registryPort) ? registryPort : null) .path("v2/{repository}/blobs/{digest}") .build().expand(repository, digest); when(mockRestTemplate.exchange( eq(blobUriComponents.toUri()), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) .thenReturn(new ResponseEntity<>(jsonResponse, HttpStatus.OK)); }
Example #5
Source File: OAuthConfiguration.java From spring-boot-microservices with Apache License 2.0 | 6 votes |
/** * Define the security that applies to the proxy */ @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() //Allow access to all static resources without authentication .antMatchers("/","/**/*.html").permitAll() .anyRequest().authenticated() .antMatchers(HttpMethod.GET, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.OPTIONS, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.POST, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PUT, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PATCH, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.DELETE, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')") .and().csrf().csrfTokenRepository(this.getCSRFTokenRepository()) .and().addFilterAfter(this.createCSRFHeaderFilter(), CsrfFilter.class); }
Example #6
Source File: AboutController.java From spring-cloud-skipper with Apache License 2.0 | 6 votes |
private String getChecksum(String defaultValue, String url, String version) { String result = defaultValue; if (result == null && StringUtils.hasText(url)) { CloseableHttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); url = constructUrl(url, version); try { ResponseEntity<String> response = new RestTemplate(requestFactory).exchange( url, HttpMethod.GET, null, String.class); if (response.getStatusCode().equals(HttpStatus.OK)) { result = response.getBody(); } } catch (HttpClientErrorException httpException) { // no action necessary set result to undefined logger.debug("Didn't retrieve checksum because", httpException); } } return result; }
Example #7
Source File: SimpleQueryClient.java From skywalking with Apache License 2.0 | 6 votes |
public Endpoints endpoints(final EndpointQuery query) throws Exception { final URL queryFileUrl = Resources.getResource("endpoints.gql"); final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8) .stream() .filter(it -> !it.startsWith("#")) .collect(Collectors.joining()) .replace("{serviceId}", query.serviceId()); final ResponseEntity<GQLResponse<Endpoints>> responseEntity = restTemplate.exchange( new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)), new ParameterizedTypeReference<GQLResponse<Endpoints>>() { } ); if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode()); } return Objects.requireNonNull(responseEntity.getBody()).getData(); }
Example #8
Source File: RestApiSession.java From sdk-rest with MIT License | 6 votes |
private synchronized JSONObject getLoginInfoFromApi() { if (loginInfo != null) { return loginInfo; } Map<String, Object> parameters = Maps.newLinkedHashMap(); parameters.put("username", restCredentials.getUsername()); try { ResponseEntity<String> response = restTemplate.exchange(LOGIN_INFO_URL, HttpMethod.GET, HttpEntity.EMPTY, String.class, parameters); if (StringUtils.isBlank(response.getBody())) { throw new RestApiException("Failed to dynamically determine REST urls with username " + restCredentials.getUsername()); } this.loginInfo = new JSONObject(response.getBody()); return this.loginInfo; } catch(RestClientException | JSONException e) { log.error("Error occurred dynamically determining REST urls with username " + restCredentials.getUsername(), e); throw new RestApiException("Failed to dynamically determine REST urls with username " + restCredentials.getUsername()); } }
Example #9
Source File: LinkisJobSubmitter.java From Qualitis with Apache License 2.0 | 6 votes |
private Map getTaskDetail(Integer taskId, String user, String ujesAddress, String clusterName) throws TaskNotExistException, ClusterInfoNotConfigException { String url = getPath(ujesAddress).path(linkisConfig.getStatus()).toString(); url = url.replace("{id}", String.valueOf(taskId)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Token-User", user); headers.add("Token-Code", getToken(clusterName)); HttpEntity entity = new HttpEntity<>(headers); LOGGER.info("Start to get job status from linkis. url: {}, method: {}, body: {}", url, javax.ws.rs.HttpMethod.GET, entity); Map response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class).getBody(); LOGGER.info("Succeed to get job status from linkis. response: {}", response); if (!checkResponse(response)) { throw new TaskNotExistException("Can not get status of task, task_id : " + taskId); } if (((Map)response.get("data")).get("task") == null) { throw new TaskNotExistException("Job id: " + taskId + " does not exist"); } return response; }
Example #10
Source File: SampleTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-14694 public void repeatedAccessToResponseViaResource() { Resource resource = new ClassPathResource("ludwig.json", this.getClass()); RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.singletonList(new ContentInterceptor(resource))); MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate) .ignoreExpectOrder(true) .bufferContent() // enable repeated reads of response body .build(); mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(resource, MediaType.APPLICATION_JSON)); restTemplate.getForObject("/composers/{id}", Person.class, 42); mockServer.verify(); }
Example #11
Source File: ConfigViewTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testRender() throws Exception { ConfigView configView = ConfigView.getInstance(); Model configData = new LinkedHashModelFactory().createEmptyModel(); configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS); Map<Object, Object> map = new LinkedHashMap<>(); map.put(ConfigView.HEADERS_ONLY, false); map.put(ConfigView.CONFIG_DATA_KEY, configData); map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod(HttpMethod.GET.name()); request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType()); MockHttpServletResponse response = new MockHttpServletResponse(); configView.render(map, request, response); String ntriplesData = response.getContentAsString(); Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES); assertThat(renderedData).isNotEmpty(); }
Example #12
Source File: ResourceHandlerFunctionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void options() throws ServletException, IOException { MockHttpServletRequest servletRequest = new MockHttpServletRequest("OPTIONS", "/"); ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter)); ServerResponse response = this.handlerFunction.handle(request); assertEquals(HttpStatus.OK, response.statusCode()); assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), response.headers().getAllow()); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context); assertNull(mav); assertEquals(200, servletResponse.getStatus()); assertEquals("GET,HEAD,OPTIONS", servletResponse.getHeader("Allow")); byte[] actualBytes = servletResponse.getContentAsByteArray(); assertEquals(0, actualBytes.length); }
Example #13
Source File: FlowableAdminApplicationSecurityTest.java From flowable-engine with Apache License 2.0 | 6 votes |
@Test public void nonAdminUserShouldBeRedirectedToIdm() { String configsUrl = "http://localhost:" + serverPort + "/flowable-admin/app/rest/server-configs"; HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.COOKIE, rememberMeCookie("user", "test-user-value")); HttpEntity<?> request = new HttpEntity<>(headers); ResponseEntity<Object> result = restTemplate.exchange(configsUrl, HttpMethod.GET, request, Object.class); assertThat(result.getStatusCode()) .as("GET server-configs") .isEqualTo(HttpStatus.FOUND); assertThat(result.getHeaders().getFirst(HttpHeaders.LOCATION)) .as("redirect location") .isEqualTo("http://localhost:8080/flowable-idm/#/login?redirectOnAuthSuccess=true&redirectUrl=" + configsUrl); }
Example #14
Source File: IuguServiceTest.java From konker-platform with Apache License 2.0 | 6 votes |
@Test public void shouldReturnErrorCreateIuguCustomer() { IuguCustomer iuguCustomer = IuguCustomer.builder() .email("[email protected]") .name("Iugu Customer") .zipCode("05500-100") .street("Avenida dos Testes") .city("São Paulo") .state("SP") .build(); HttpEntity<IuguCustomer> request = new HttpEntity<>(iuguCustomer); ResponseEntity<IuguCustomer> responseEntity = ResponseEntity.badRequest().body(null); when(restTemplate.exchange("https://api.iugu.com/v1/customers?api_token=b17421313f9a8db907afa7b7047fbcd8", HttpMethod.POST, request, IuguCustomer.class)) .thenReturn(responseEntity); ServiceResponse<IuguCustomer> response = iuguService.createIuguCustomer(iuguCustomer); Assert.assertThat(response, hasErrorMessage(IuguService.Validations.IUGU_CUSTOMER_CREATION_ERROR.getCode())); }
Example #15
Source File: ApplicationConfigurationMetadataResolverAutoConfigurationTest.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@Test public void containerImageMetadataResolverWithActiveSSL() throws URISyntaxException { assertThat(containerImageMetadataResolver).isNotNull(); Map<String, String> labels = containerImageMetadataResolver.getImageLabels("demo.goharbor.io/test/image:1.0.0"); assertThat(labels).containsExactly(Collections.singletonMap("foo", "bar").entrySet().iterator().next()); // Determine the OAuth2 token service entry point. verify(noSslVerificationContainerRestTemplate) .exchange(eq(new URI("https://demo.goharbor.io/v2/_catalog")), eq(HttpMethod.GET), any(), eq(Map.class)); // Get authorization token verify(containerRestTemplate).exchange( eq(new URI("https://demo.goharbor.io/service/token?service=demo-registry2&scope=repository:test/image:pull")), eq(HttpMethod.GET), any(), eq(Map.class)); // Get Manifest verify(containerRestTemplate).exchange(eq(new URI("https://demo.goharbor.io/v2/test/image/manifests/1.0.0")), eq(HttpMethod.GET), any(), eq(Map.class)); // Get Blobs verify(containerRestTemplate).exchange(eq(new URI("https://demo.goharbor.io/v2/test/image/blobs/test_digest")), eq(HttpMethod.GET), any(), eq(String.class)); }
Example #16
Source File: CorsConfiguration.java From spring-analysis-note with MIT License | 6 votes |
/** * By default a newly created {@code CorsConfiguration} does not permit any * cross-origin requests and must be configured explicitly to indicate what * should be allowed. * <p>Use this method to flip the initialization model to start with open * defaults that permit all cross-origin requests for GET, HEAD, and POST * requests. Note however that this method will not override any existing * values already set. * <p>The following defaults are applied if not already set: * <ul> * <li>Allow all origins.</li> * <li>Allow "simple" methods {@code GET}, {@code HEAD} and {@code POST}.</li> * <li>Allow all headers.</li> * <li>Set max age to 1800 seconds (30 minutes).</li> * </ul> */ public CorsConfiguration applyPermitDefaultValues() { if (this.allowedOrigins == null) { this.allowedOrigins = DEFAULT_PERMIT_ALL; } if (this.allowedMethods == null) { this.allowedMethods = DEFAULT_PERMIT_METHODS; this.resolvedMethods = DEFAULT_PERMIT_METHODS .stream().map(HttpMethod::resolve).collect(Collectors.toList()); } if (this.allowedHeaders == null) { this.allowedHeaders = DEFAULT_PERMIT_ALL; } if (this.maxAge == null) { this.maxAge = 1800L; } return this; }
Example #17
Source File: TaskControllerIntTest.java From taskana with Apache License 2.0 | 6 votes |
@Test void testGetAllTasksByWorkbasketIdWithinSinglePlannedTimeInterval() { Instant plannedFromInstant = Instant.now().minus(6, ChronoUnit.DAYS); Instant plannedToInstant = Instant.now().minus(3, ChronoUnit.DAYS); ResponseEntity<TaskanaPagedModel<TaskSummaryRepresentationModel>> response = TEMPLATE.exchange( restHelper.toUrl(Mapping.URL_TASKS) + "?workbasket-id=WBI:100000000000000000000000000000000001" + "&planned-from=" + plannedFromInstant + "&planned-until=" + plannedToInstant + "&sort-by=planned", HttpMethod.GET, restHelper.defaultRequest(), TASK_SUMMARY_PAGE_MODEL_TYPE); assertThat(response.getBody()).isNotNull(); assertThat((response.getBody()).getLink(IanaLinkRelations.SELF)).isNotNull(); assertThat(response.getBody().getContent()).hasSize(3); }
Example #18
Source File: JwtSecurityConfiguration.java From flair-engine with Apache License 2.0 | 5 votes |
@Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers("/app/**/*.{js,html}") .antMatchers("/i18n/**") .antMatchers("/content/**") .antMatchers("/swagger-ui/index.html") .antMatchers("/test/**"); }
Example #19
Source File: OpencpsCallServiceInfoRestFacadeImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override protected ServiceInfoResponse makeServiceCall(CommonRequest payload) throws UpstreamServiceTimedOutException, UpstreamServiceFailedException { MultiValueMap<String, String> urlQueryParams = new LinkedMultiValueMap<>(); String endPoint = Validator.isNotNull(payload.getEndpoint()) ? payload.getEndpoint() : DossierStatisticConfig.get(DossierStatisticConstants.SERVICE_INFO_ENDPOINT); // get the params for EE HashMap<String, String> urlPathSegments = new HashMap<>(); //urlPathSegments.put("s", payload.getKeyword()); // build the url String url = buildUrl(endPoint, urlPathSegments, urlQueryParams) + StringPool.FORWARD_SLASH + payload.getKeyword(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(DossierStatisticConstants.GROUP_ID, Long.toString(payload.getGroupId())); // if (Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY)) // && Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET))) { // setHttpHeadersAuthorization(httpHeaders, PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY), PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET)); // } // else { // httpHeaders.add("Authorization", "Basic " + DossierStatisticConfig.get(DossierStatisticConstants.OPENCPS_AUTHENCATION)); // } if (Validator.isNotNull(payload.getUsername()) && Validator.isNotNull(payload.getPassword())) { httpHeaders.add("Authorization", "Basic " + Base64.getEncoder().encodeToString((payload.getUsername() + ":" + payload.getPassword()).getBytes())); } return executeGenericRestCall(url, HttpMethod.GET, httpHeaders, payload, ServiceInfoResponse.class).getBody(); }
Example #20
Source File: FormTag.java From lams with GNU General Public License v2.0 | 5 votes |
private void assertHttpMethod(String method) { for (HttpMethod httpMethod : HttpMethod.values()) { if (httpMethod.name().equalsIgnoreCase(method)) { return; } } throw new IllegalArgumentException("Invalid HTTP method: " + method); }
Example #21
Source File: DefaultCorsProcessorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void preflightRequestWithoutRequestMethod() throws Exception { this.request.setMethod(HttpMethod.OPTIONS.name()); this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1"); this.processor.processRequest(this.conf, this.request, this.response); assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS)); assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); }
Example #22
Source File: AsyncHttpOperations.java From riptide with MIT License | 5 votes |
private <T> ListenableFuture<T> execute(final URI url, final HttpMethod method, @Nullable final Entity entity, final Route route, final Function<ClientHttpResponse, T> function) { final CompletableFuture<T> future = http.execute(method, url) .body(entity) .call(route(route)) .thenApply(function); return new CompletableToListenableFutureAdapter<>(future); }
Example #23
Source File: SecurityConfig.java From spring-security-oauth with MIT License | 5 votes |
@Override protected void configure(HttpSecurity http) throws Exception {// @formatter:off http.cors() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/api/foos") .hasAuthority("SCOPE_write") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt(); }
Example #24
Source File: AddInspectionRoutePointSMOImpl.java From MicroCommunity with Apache License 2.0 | 5 votes |
@Override protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) { ResponseEntity<String> responseEntity = null; super.validateStoreStaffCommunityRelationship(pd, restTemplate); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), ServiceConstant.SERVICE_API_URL + "/api/inspectionRoute.saveInspectionRoutePoint", HttpMethod.POST); return responseEntity; }
Example #25
Source File: RestaurantControllerIntegrationTests.java From Mastering-Microservices-with-Java-Third-Edition with MIT License | 5 votes |
/** * Test the GET /v1/restaurants/{id} API for no content */ @Test public void testGetById_NoContent() { HttpHeaders headers = new HttpHeaders(); HttpEntity<Object> entity = new HttpEntity<>(headers); ResponseEntity<Map> responseE = restTemplate .exchange("http://localhost:" + port + "/v1/restaurants/99", HttpMethod.GET, entity, Map.class); assertNotNull(responseE); // Should return no content as there is no restaurant with id 99 assertEquals(HttpStatus.NO_CONTENT, responseE.getStatusCode()); }
Example #26
Source File: ServletContainerConfiguration.java From haven-platform with Apache License 2.0 | 5 votes |
@Override protected void configure(HttpSecurity http) throws Exception { final String uiPrefix = "/ui/"; final String loginUrl = uiPrefix + "login.html"; TokenAuthFilterConfigurer<HttpSecurity> tokenFilterConfigurer = new TokenAuthFilterConfigurer<>(new RequestTokenHeaderRequestMatcher(), new TokenAuthProvider(tokenValidator, userDetailsService, authProcessor)); http.csrf().disable() .authenticationProvider(provider).userDetailsService(userDetailsService) .anonymous().principal(SecurityUtils.USER_ANONYMOUS).and() .authorizeRequests().antMatchers(uiPrefix + "/token/login").permitAll() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()//allow CORS option calls .antMatchers(uiPrefix + "**").authenticated() .and().headers().cacheControl().disable() .and().formLogin().loginPage(loginUrl).permitAll().defaultSuccessUrl(uiPrefix) .and().logout().logoutUrl(uiPrefix + "logout").logoutSuccessUrl(loginUrl) .and().apply(tokenFilterConfigurer); // enable after testing // .and().sessionManagement() // .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // X-Frame-Options http.headers() .frameOptions().sameOrigin(); http.addFilterAfter(new AccessContextFilter(aclContextFactory), SwitchUserFilter.class); //we use basic in testing and scripts if (basicAuthEnable) { http.httpBasic(); } }
Example #27
Source File: HiddenHttpMethodFilter.java From spring-analysis-note with MIT License | 5 votes |
/** * Transform an HTTP POST into another method based on {@code methodParamName}. * @param exchange the current server exchange * @param chain provides a way to delegate to the next filter * @return {@code Mono<Void>} to indicate when request processing is complete */ @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { if (exchange.getRequest().getMethod() != HttpMethod.POST) { return chain.filter(exchange); } return exchange.getFormData() .map(formData -> { String method = formData.getFirst(this.methodParamName); return StringUtils.hasLength(method) ? mapExchange(exchange, method) : exchange; }) .flatMap(chain::filter); }
Example #28
Source File: ProjectGenerationStatPublisherTests.java From initializr with Apache License 2.0 | 5 votes |
@Test void fatalErrorOnlyLogs() { ProjectRequest request = createProjectRequest(); ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, this.metadata); this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2, Collections.singletonMap(Exception.class, true))); this.mockServer.expect(requestTo("https://example.com/elastic/initializr/request")) .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); this.mockServer.expect(requestTo("https://example.com/elastic/initializr/request")) .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); this.statPublisher.handleEvent(event); this.mockServer.verify(); }
Example #29
Source File: AwsIamAuthenticationUnitTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldUsingAuthenticationSteps() { this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.iam_http_request_method").value("POST")) .andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists()) .andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role")) .andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body( "{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}")); AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role") .credentials(new BasicAWSCredentials("foo", "bar")).build(); AuthenticationSteps steps = AwsIamAuthentication.createAuthenticationSteps(options); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, this.restTemplate); VaultToken login = executor.login(); assertThat(login).isInstanceOf(LoginToken.class); assertThat(login.getToken()).isEqualTo("my-token"); assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10)); assertThat(((LoginToken) login).isRenewable()).isTrue(); }
Example #30
Source File: RestTemplateIntegrationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void notFound() { try { template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); fail("HttpClientErrorException expected"); } catch (HttpClientErrorException ex) { assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); assertNotNull(ex.getStatusText()); assertNotNull(ex.getResponseBodyAsString()); } }