Work from the http security object and enable or disable CSRF handling,
as requested in the application properties.

@param http the http security object
@return the http security object
@throws Exception if there is a problem
501597
private HttpSecurity handleCsrf(final HttpSecurity http)
            throws Exception {
        if ("test".equals(activeProfile)) {
            return http.csrf().disable();
        } else {
            return http.csrf().ignoringAntMatchers(
                        "/gedbrowserng/v1/login",
                        "/gedbrowserng/v1/signup")
                    .csrfTokenRepository(
                            CookieCsrfTokenRepository.withHttpOnlyFalse())
                    .and();
        }
    }
1042732
@Bean
	public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
		return http
			.authorizeExchange()
				.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
				.pathMatchers("/foo", "/bar")
					.authenticated().and()
				.formLogin().and()
			.build();
	}
416368
def process_exception(self, request, exception):
        
        if isinstance(exception, HttpRedirectRequest):
            return HttpResponseRedirect(exception.url, status=exception.status)
        else:
            return None
960791
public HashMap<String, String> ssoTokenGenerator() throws Exception {
        String protocol = "https://";
        HashMap<String, String> cookieToken = new HashMap<>();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
        HttpClient client = HttpClientBuilder.create()
                .setSslcontext(sslContext)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).setCircularRedirectsAllowed(true).build()).build();
        try {
            HttpResponse firstResponse = client.execute(httpGet, context);

            logger.debug(firstResponse.getStatusLine().toString());
            Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
            Elements code = doc.select("[name=lt]");
            String loginCode = code.attr("value");
            String executionCode = doc.select("[name=execution]").attr("value");
            for (Header oneHeader : firstResponse.getAllHeaders()) {
                logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
            }

            URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("_eventId", "submit"));
            params.add(new BasicNameValuePair("submit", "LOGIN"));
            params.add(new BasicNameValuePair("username", userName));
            params.add(new BasicNameValuePair("password", passWord));

            if (tenant != null) {
                params.add(new BasicNameValuePair("tenant", tenant));
            }

            params.add(new BasicNameValuePair("lt", loginCode));
            params.add(new BasicNameValuePair("execution", executionCode));
            HttpPost httpPost = new HttpPost(redirect);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse secondResponse = client.execute(httpPost, context);

            for (Header oneHeader : secondResponse.getAllHeaders()) {
                logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
            }

            HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
            client.execute(managementGet, context);

            for (Cookie oneCookie : context.getCookieStore().getCookies()) {
                logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
                cookieToken.put(oneCookie.getName(), oneCookie.getValue());
            }

        } catch (Exception e) {
            e.getStackTrace();
        }
        return cookieToken;
    }
461492
public XcapResponseImpl handleResponse(HttpResponse httpResponse)
			throws ClientProtocolException, IOException {

		int statusCode = httpResponse.getStatusLine().getStatusCode();

		String eTag = null;
		String mimetype = null;
		if (statusCode == 200 || statusCode == 201) {
			// sucessful response
			org.apache.http.Header eTagHeader = httpResponse
					.getFirstHeader(XcapConstant.HEADER_ETAG);
			if (eTagHeader != null) {
				eTag = eTagHeader.getValue();
			}
			org.apache.http.Header mimetypeHeader = httpResponse
			.getFirstHeader(XcapConstant.HEADER_CONTENT_TYPE);
			if (mimetypeHeader != null) {
				mimetype = mimetypeHeader.getValue();
			}
		}

		final org.apache.http.Header[] apacheHeaders = httpResponse
				.getAllHeaders();
		final Header[] headers = new Header[apacheHeaders.length];
		for (int i = 0; i < headers.length; i++) {
			headers[i] = new HeaderImpl(apacheHeaders[i]);
		}

		final HttpEntity httpEntity = httpResponse.getEntity();

		final XcapEntityImpl xcapEntity = httpEntity != null ? new XcapEntityImpl(
				httpEntity)
				: null;

		return new XcapResponseImpl(statusCode, eTag, mimetype, headers, xcapEntity);
	}
906120
public void setAuthentication(HttpURLConnection http) {
		
		if(user == null || pass == null 
				|| user.length() <= 0 || pass.length() <= 0) {
			return;
		}

		String base64login = Base64.encode(user + ":" + pass);

		http.addRequestProperty("Authorization", "Basic " + base64login);
		
	}
782699
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        getHttpContext().checkSecurityConstraints(pathInContext,request,response);
    }
163277
public HttpResponse perform(HttpRequest request) throws IOException, HttpClientException {
		
		// first check if the request is a multipart/form-data and the method is
		// not POST: if so, there's something inconsistent and we just bail out
		if(request.isMultiPartFormData() && request.getMethod() != HttpMethod.POST) {
			logger.error("multipart/form-data can only be conveyed through a POST, using {} instead", request.getMethod().name());
			throw new HttpClientException("multipart/form-data cannot be conveyed through a " + request.getMethod().name() + " request");
		}
		
		URL url = request.getURL();		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy != null ? proxy : Proxy.NO_PROXY);
		// optional default is GET
		connection.setRequestMethod(request.getMethod().name());
		for(Entry<String, String> header : request.getHeaders().entrySet()) {
			connection.setRequestProperty(header.getKey(), header.getValue());
		}
		
		if(request.getMethod() == HttpMethod.POST) {
			// add headers directly to the connection (we've already looped over
			// headers in the request object, so it's too late to add headers now)
			if(request.isMultiPartFormData()) {
				connection.setRequestProperty("Content-type", "multipart/form-data, boundary=" + request.getBoundary());
			} else {
				connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			}
						
			connection.setDoOutput(true);
//			try(MirrorOutputStream mirror = new MirrorOutputStream(connection.getOutputStream(), new FileOutputStream("target/request.dat")); DataOutputStream stream = new DataOutputStream(mirror)) {
			try(DataOutputStream stream = new DataOutputStream(connection.getOutputStream())) {
				if(request.isMultiPartFormData()) {
					//
					// multipart/form-encoded format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: multipart/form-data, boundary=<RANDOM BOUNDARY>
					// Content-Length: <REQUEST_LENGTH>
					//
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field1"
					//
					// value1
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="field2"
					//
					// value2
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file1"; filename="<NAME OF FILE 1>"
					// Content-Type: <FILE 1 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 1 BINARY DATA>
					// --<RANDOM BOUNDARY>
					// Content-Disposition: form-data; name="file2"; filename="<NAME OF FILE 2>"
					// Content-Type: <FILE 2 MIME TYPE>
					// Content-Transfer-Encoding: binary
					// 
					// <FILE 2 BINARY DATA>
					// --<RANDOM BOUNDARY>--
					// ==========================						
					for(HttpParameter parameter : request.getParameters()) {
						stream.writeBytes("--" + request.getBoundary());
						stream.writeBytes(NEWLINE);
						switch(parameter.getType()) {
						case TEXT:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"" + NEWLINE);
							stream.writeBytes(NEWLINE);
							stream.writeBytes(((HttpTextParameter)parameter).getValue().toString() + NEWLINE);
							break;
						case FILE:
							stream.writeBytes("Content-Disposition: form-data; name=\"" + parameter.getName() + "\"; filename=\"" + ((HttpFileParameter)parameter).getFileName() + "\"" + NEWLINE);
							stream.writeBytes("Content-Type: " + ((HttpFileParameter)parameter).getContentType() + NEWLINE);
							stream.writeBytes("Content-Transfer-Encoding: binary" + NEWLINE);
							stream.writeBytes(NEWLINE);
							Streams.copy(((HttpFileParameter)parameter).getInputStream(), stream);
							stream.writeBytes(NEWLINE);
							break;						
						}
					}					
					stream.writeBytes("--" + request.getBoundary() + "--");
				} else {
					//
					// plain old form format is:
					//
					// ========================
					// POST /path/to/script.php HTTP/1.0
					// Host: example.com
					// Content-type: application/x-www-form-urlencoded
					// Content-Length: <CONTENT LENGTH>
					//
					// logfile=blabla&configfile=more+blabla&usercomment=hello&useremail=
					// ==========================						
					//
					String values = HttpParameter.concatenate(request.getParameters());
					stream.writeBytes(values);
				}
			
				stream.flush();
				stream.close();
			}
		} else if(request.getMethod() == HttpMethod.GET) {
			// do nothing
		}
		
		return new HttpResponse(connection);
	}
184153
@Override
    public ClientHttpResponse intercept(
            HttpRequest req, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        Assert.notNull(propertyResolver);
        Assert.notNull(id);

        try {
            String authString = getOAuthAuthString(req);
            req.getHeaders().add(Headers.Authorization.name(), authString);
        } catch (Exception e) {
            throw new IOException("Error building OAuth header", e);
        }

        return execution.execute(req, body);
    }
65939
protected Optional<MutableHttpResponse<?>> handleRequest(HttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        if (originHeader.isPresent()) {

            String requestOrigin = originHeader.get();
            boolean preflight = CorsUtil.isPreflightRequest(request);

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                HttpMethod requestMethod = request.getMethod();

                List<HttpMethod> allowedMethods = config.getAllowedMethods();

                if (!isAnyMethod(allowedMethods)) {
                    HttpMethod methodToMatch = preflight ? headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class).orElse(requestMethod) : requestMethod;
                    if (allowedMethods.stream().noneMatch(method -> method.equals(methodToMatch))) {
                        return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                    }
                }

                if (preflight) {
                    Optional<List> accessControlHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));

                    List<String> allowedHeaders = config.getAllowedHeaders();

                    if (!isAny(allowedHeaders) && accessControlHeaders.isPresent()) {
                        if (!accessControlHeaders.get().stream()
                            .allMatch(header -> allowedHeaders.stream()
                                .anyMatch(allowedHeader -> allowedHeader.equals(header.toString().trim())))) {
                            return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                        }
                    }

                    MutableHttpResponse<Object> ok = HttpResponse.ok();
                    handleResponse(request, ok);
                    return Optional.of(ok);
                }
            }
        }

        return Optional.empty();
    }
1214554
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(OAUTH2_ACTION)) {
			String authCode = request.getParameter("code");
			if (!StringUtils.isBlank(authCode)) {
				String appid = SecurityUtils.getAppidFromAuthRequest(request);
				String redirectURI = SecurityUtils.getRedirectUrl(request);
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.OAUTH2_PREFIX);
				String entity = Utils.formatMessage(PAYLOAD,
						authCode, Utils.urlEncode(redirectURI),
						URLEncoder.encode(SecurityUtils.getSettingForApp(app, "security.oauth.scope", ""), "UTF-8"),
						keys[0], keys[1]);

				String acceptHeader = SecurityUtils.getSettingForApp(app, "security.oauth.accept_header", "");
				HttpPost tokenPost = new HttpPost(SecurityUtils.getSettingForApp(app, "security.oauth.token_url", ""));
				tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
				tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
				if (!StringUtils.isBlank(acceptHeader)) {
					tokenPost.setHeader(HttpHeaders.ACCEPT, acceptHeader);
				}

				try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
					if (resp1 != null && resp1.getEntity() != null) {
						Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
						if (token != null && token.containsKey("access_token")) {
							userAuth = getOrCreateUser(app, (String) token.get("access_token"));
						}
						EntityUtils.consumeQuietly(resp1.getEntity());
					}
				}
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
72514
public base_response loginchallengeresponse(String response) throws Exception
	{
		loginchallengeresponse logincr = new loginchallengeresponse(response);
		base_response result = logincr.perform_operation(this);
		if (result.errorcode == 0)
			this.sessionid = result.sessionid;
		return result;
	}
1285478
private static void request(final Request request) {
        if (null == request) {
            WonderPush.logError("Request with null request.");
            return;
        }

        WonderPush.safeDefer(new Runnable() {
            @Override
            public void run() {
                // Decorate parameters
                WonderPushRequestParamsDecorator.decorate(request.getResource(), request.getParams());

                // Generate signature
                BasicHeader authorizationHeader = request.getAuthorizationHeader();

                // Headers
                BasicHeader[] headers = null;
                if (null != authorizationHeader) {
                    headers = new BasicHeader[1];
                    headers[0] = authorizationHeader;
                }

                String url = WonderPushUriHelper.getAbsoluteUrl(request.getResource());
                WonderPush.logDebug("requesting url: " + request.getMethod() + " " + url + "?" + request.getParams().getURLEncodedString());
                // TODO: support other contentTypes such as "application/json"
                String contentType = "application/x-www-form-urlencoded";

                // Handler
                final ResponseHandler handler = request.getHandler();
                HttpEntity entity = null;
                if (request.getParams() != null) {
                    try {
                        entity = request.getParams() != null ? request.getParams().getEntity(null) : null;
                    } catch (IOException ex) {
                        WonderPush.logError("Failed to create HttpEntity from params " + request.getParams(), ex);
                        if (handler != null) {
                            handler.onFailure(ex, new Response(""));
                        }
                        return;
                    }
                }
                final long sendDate = SystemClock.elapsedRealtime();
                JsonHttpResponseHandler jsonHandler = new JsonHttpResponseHandler() {
                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        // mute this
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        syncTime(response);
                        WonderPush.setNetworkAvailable(true);
                        if (handler != null) {
                            handler.onSuccess(statusCode, new Response(response));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                        WonderPush.logError("Unexpected JSONArray answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + response.length() + ") " + response.toString());
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        WonderPush.logError("Error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: " + errorResponse);
                        syncTime(errorResponse);
                        WonderPush.logDebug("Request Error: " + errorResponse);
                        WonderPush.setNetworkAvailable(errorResponse != null);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(errorResponse));
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                        WonderPush.logError("Unexpected JSONArray error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + errorResponse.length() + ") " + errorResponse.toString());
                        this.onFailure(statusCode, headers, errorResponse.toString(), throwable);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        WonderPush.logError("Unexpected string error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                        WonderPush.setNetworkAvailable(false);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(responseString));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        WonderPush.logError("Unexpected string answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                    }

                    private void syncTime(JSONObject data) {
                        long recvDate = SystemClock.elapsedRealtime();
                        if (data == null || !data.has("_serverTime")) {
                            return;
                        }
                        TimeSync.syncTimeWithServer(sendDate, recvDate, data.optLong("_serverTime"), data.optLong("_serverTook"));
                    }
                };
                // NO UNNECESSARY WORK HERE, because of timed request
                switch (request.getMethod()) {
                    case GET:
                        sClient.get(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    case PUT:
                        sClient.put(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case POST:
                        sClient.post(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case PATCH:
                        sClient.patch(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case DELETE:
                        sClient.delete(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    default:
                        jsonHandler.sendFailureMessage(0, null, null, new UnsupportedOperationException("Unhandled method " + request.getMethod()));
                }
            }
        }, 0);
    }
1340549
@SuppressWarnings("deprecation")
    private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" },
            null,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Registry registry = RegistryBuilder.create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();
        HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
        CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(50)
            .setMaxConnTotal(100)
            .setConnectionManager(httpClientConnectionManager)
            .build();
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build();
        getMethod.setConfig(requestConfig);
        HttpResponse response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
            String result = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
        }
        return response;
    }
416435
def enforce_csrf(self, request):
        
        reason = CSRFCheck().process_view(request, None, (), {})
        if reason:
            # CSRF failed, bail with explicit error message
            raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
1302634
public static HttpResponse doGetResponse(String url) throws Exception {
        return doGetResponse(url, null, null, null);
    }
315833
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException {

        HttpHead headMethod = new HttpHead(uri);
        MyRedirectHandler redirectHandler = new MyRedirectHandler(uri);

        String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*";
        CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingConnManager)
            .setSSLContext(ssl)
            .setRedirectStrategy(redirectHandler)
            .setDefaultHeaders(Arrays.asList(
                new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything
                new BasicHeader("User-Agent", "Mozilla/5.0"),
                new BasicHeader("Upgrade-Insecure-Requests", "1")       // we are an all trusting client...
            ))
            .build();

        HttpResponse httpResponse = httpClient.execute(headMethod);
        redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x)));
        return httpResponse;
    }