Java Code Examples for org.springframework.http.HttpHeaders#remove()

The following examples show how to use org.springframework.http.HttpHeaders#remove() . 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: AuthRequestInterceptor.java    From staffjoy with MIT License 6 votes vote down vote up
private String setAuthHeader(RequestData data, MappingProperties mapping) {
    // default to anonymous web when prove otherwise
    String authorization = AuthConstant.AUTHORIZATION_ANONYMOUS_WEB;
    HttpHeaders headers = data.getHeaders();
    Session session = this.getSession(data.getOriginRequest());
    if (session != null) {
        if (session.isSupport()) {
            authorization = AuthConstant.AUTHORIZATION_SUPPORT_USER;
        } else {
            authorization = AuthConstant.AUTHORIZATION_AUTHENTICATED_USER;
        }

        this.checkBannedUsers(session.getUserId());

        headers.set(AuthConstant.CURRENT_USER_HEADER, session.getUserId());
    } else {
        // prevent hacking
        headers.remove(AuthConstant.CURRENT_USER_HEADER);
    }
    headers.set(AuthConstant.AUTHORIZATION_HEADER, authorization);

    return authorization;
}
 
Example 2
Source File: LoginController.java    From open-cloud with MIT License 6 votes vote down vote up
public JSONObject getToken(String userName, String password, String type, HttpHeaders headers) {
    OpenOAuth2ClientDetails clientDetails =  clientProperties.getOauth2().get("portal");
    String url = WebUtils.getServerUrl(WebUtils.getHttpServletRequest()) + "/oauth/token";
    // 使用oauth2密码模式登录.
    MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
    postParameters.add("username", userName);
    postParameters.add("password", password);
    postParameters.add("client_id", clientDetails.getClientId());
    postParameters.add("client_secret", clientDetails.getClientSecret());
    postParameters.add("grant_type", "password");
    // 添加参数区分,第三方登录
    postParameters.add("login_type", type);
    // 使用客户端的请求头,发起请求
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    // 强制移除 原来的请求头,防止token失效
    headers.remove(HttpHeaders.AUTHORIZATION);
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers);
    JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);
    return result;
}
 
Example 3
Source File: LoginController.java    From open-cloud with MIT License 6 votes vote down vote up
public JSONObject getToken(String userName, String password, String type, HttpHeaders headers) {
    OpenOAuth2ClientDetails clientDetails =  clientProperties.getOauth2().get("admin");
    String url = WebUtils.getServerUrl(WebUtils.getHttpServletRequest()) + "/oauth/token";
    // 使用oauth2密码模式登录.
    MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
    postParameters.add("username", userName);
    postParameters.add("password", password);
    postParameters.add("client_id", clientDetails.getClientId());
    postParameters.add("client_secret", clientDetails.getClientSecret());
    postParameters.add("grant_type", "password");
    // 添加参数区分,第三方登录
    postParameters.add("login_type", type);
    // 使用客户端的请求头,发起请求
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    // 强制移除 原来的请求头,防止token失效
    headers.remove(HttpHeaders.AUTHORIZATION);
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers);
    JSONObject result = restTemplate.postForObject(url, request, JSONObject.class);
    return result;
}
 
Example 4
Source File: RequestForwarder.java    From staffjoy with MIT License 5 votes vote down vote up
/**
 * Remove any protocol-level headers from the remote server's response that
 * do not apply to the new response we are sending.
 *
 * @param response
 */
protected void prepareForwardedResponseHeaders(ResponseData response) {
    HttpHeaders headers = response.getHeaders();
    headers.remove(TRANSFER_ENCODING);
    headers.remove(CONNECTION);
    headers.remove("Public-Key-Pins");
    headers.remove(SERVER);
    headers.remove("Strict-Transport-Security");
}
 
Example 5
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 6
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 7
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(inputMessage.getServletRequest(), outputMessage.getServletResponse());
	HttpHeaders responseHeaders = outputMessage.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (inputMessage.getMethod() == HttpMethod.GET || inputMessage.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 8
Source File: CommonResponseProtocolHeadersRewriter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
void rewriteHeaders(HttpHeaders headers, Consumer<HttpHeaders> headersSetter) {
    HttpHeaders rewrittenHeaders = copyHeaders(headers);
    rewrittenHeaders.remove(TRANSFER_ENCODING);
    rewrittenHeaders.remove(CONNECTION);
    rewrittenHeaders.remove(PUBLIC_KEY_PINS);
    rewrittenHeaders.remove(SERVER);
    rewrittenHeaders.remove(STRICT_TRANSPORT_SECURITY);
    headersSetter.accept(rewrittenHeaders);
    log.debug("Response headers rewritten from {} to {}", headers, rewrittenHeaders);
}
 
Example 9
Source File: CommonRequestProtocolHeadersRewriter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
void rewriteHeaders(HttpHeaders headers, Consumer<HttpHeaders> headersSetter) {
    HttpHeaders rewrittenHeaders = copyHeaders(headers);
    rewrittenHeaders.set(CONNECTION, "close");
    rewrittenHeaders.remove(TE);
    headersSetter.accept(rewrittenHeaders);
    log.debug("Request headers rewritten from {} to {}", headers, rewrittenHeaders);
}
 
Example 10
Source File: CommonRemovingResponseCookiesRewriter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
void removeCookies(HttpHeaders headers, String cookieHeaderName, Consumer<HttpHeaders> headersSetter) {
    HttpHeaders rewrittenHeaders = copyHeaders(headers);
    List<String> removedCookies = rewrittenHeaders.remove(cookieHeaderName);
    if (isNotEmpty(removedCookies)) {
        headersSetter.accept(rewrittenHeaders);
        log.debug("Cookies {} removed from response", removedCookies);
    }
}
 
Example 11
Source File: AviAuthorizationInterceptor.java    From sdk with Apache License 2.0 4 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
		throws IOException {
	if (null == this.aviCredentials.getSessionID() || this.aviCredentials.getSessionID().isEmpty()) {
		AviRestUtils.authenticateSession(this.aviCredentials);
	}
	HttpHeaders headers = request.getHeaders();
	headers.add("Content-Type", "application/json");
	headers.add("X-Avi-Version", this.aviCredentials.getVersion());
	headers.add("X-Avi-Tenant", this.aviCredentials.getTenant());
	headers.add("X-CSRFToken", this.aviCredentials.getCsrftoken());
	headers.add("Referer", AviRestUtils.getControllerURL(this.aviCredentials));
	headers.add(HttpHeaders.COOKIE, "csrftoken=" + this.aviCredentials.getCsrftoken() + "; " + "avi-sessionid="
			+ this.aviCredentials.getSessionID());
	
	ClientHttpResponse response = execution.execute(request, body);
	
	int responseCode = response.getRawStatusCode();
	
	if (Arrays.asList(419, 401).contains(responseCode)) {
		this.numApiExecCount++;
		while (numApiExecCount < this.aviCredentials.getNumApiRetries()) {
			headers.remove("X-CSRFToken");
			headers.remove("Cookie");
			AviRestUtils.authenticateSession(this.aviCredentials);
			headers.add("X-CSRFToken", this.aviCredentials.getCsrftoken());
			headers.add("Cookie", "csrftoken=" + this.aviCredentials.getCsrftoken() + "; " + "avi-sessionid="
					+ this.aviCredentials.getSessionID());
			response = execution.execute(request, body);
			if (Arrays.asList(419, 401).contains(response.getRawStatusCode())) {
				this.numApiExecCount++;
				continue;
			}
			else {
				break;
			}
		}
	}

	return response;
}
 
Example 12
Source File: ModifyRequestBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			Class inClass = config.getInClass();
			ServerRequest serverRequest = ServerRequest.create(exchange,
					messageReaders);

			// TODO: flux or mono
			Mono<?> modifiedBody = serverRequest.bodyToMono(inClass)
					.flatMap(originalBody -> config.getRewriteFunction()
							.apply(exchange, originalBody))
					.switchIfEmpty(Mono.defer(() -> (Mono) config.getRewriteFunction()
							.apply(exchange, null)));

			BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody,
					config.getOutClass());
			HttpHeaders headers = new HttpHeaders();
			headers.putAll(exchange.getRequest().getHeaders());

			// the new content type will be computed by bodyInserter
			// and then set in the request decorator
			headers.remove(HttpHeaders.CONTENT_LENGTH);

			// if the body is changing content types, set it here, to the bodyInserter
			// will know about it
			if (config.getContentType() != null) {
				headers.set(HttpHeaders.CONTENT_TYPE, config.getContentType());
			}
			CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
					exchange, headers);
			return bodyInserter.insert(outputMessage, new BodyInserterContext())
					// .log("modify_request", Level.INFO)
					.then(Mono.defer(() -> {
						ServerHttpRequest decorator = decorate(exchange, headers,
								outputMessage);
						return chain
								.filter(exchange.mutate().request(decorator).build());
					})).onErrorResume(
							(Function<Throwable, Mono<Void>>) throwable -> release(
									exchange, outputMessage, throwable));
		}

		@Override
		public String toString() {
			return filterToStringCreator(ModifyRequestBodyGatewayFilterFactory.this)
					.append("Content type", config.getContentType())
					.append("In class", config.getInClass())
					.append("Out class", config.getOutClass()).toString();
		}
	};
}
 
Example 13
Source File: RequestForwarder.java    From staffjoy with MIT License 2 votes vote down vote up
/**
 * Remove any protocol-level headers from the clients request that
 * do not apply to the new request we are sending to the remote server.
 *
 * @param request
 * @param destination
 */
protected void prepareForwardedRequestHeaders(RequestData request, ForwardDestination destination) {
    HttpHeaders headers = request.getHeaders();
    //headers.set(HOST, destination.getUri().getAuthority());
    headers.remove(TE);
}