001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.server.session; 018 019import java.util.Collections; 020import java.util.List; 021 022import org.springframework.http.HttpHeaders; 023import org.springframework.util.Assert; 024import org.springframework.web.server.ServerWebExchange; 025 026/** 027 * Request and response header-based {@link WebSessionIdResolver}. 028 * 029 * @author Greg Turnquist 030 * @author Rob Winch 031 * @since 5.0 032 */ 033public class HeaderWebSessionIdResolver implements WebSessionIdResolver { 034 035 /** Default value for {@link #setHeaderName(String)}. */ 036 public static final String DEFAULT_HEADER_NAME = "SESSION"; 037 038 039 private String headerName = DEFAULT_HEADER_NAME; 040 041 042 /** 043 * Set the name of the session header to use for the session id. 044 * The name is used to extract the session id from the request headers as 045 * well to set the session id on the response headers. 046 * <p>By default set to {@code DEFAULT_HEADER_NAME} 047 * @param headerName the header name 048 */ 049 public void setHeaderName(String headerName) { 050 Assert.hasText(headerName, "'headerName' must not be empty"); 051 this.headerName = headerName; 052 } 053 054 /** 055 * Return the configured header name. 056 * @return the configured header name 057 */ 058 public String getHeaderName() { 059 return this.headerName; 060 } 061 062 063 @Override 064 public List<String> resolveSessionIds(ServerWebExchange exchange) { 065 HttpHeaders headers = exchange.getRequest().getHeaders(); 066 return headers.getOrDefault(getHeaderName(), Collections.emptyList()); 067 } 068 069 @Override 070 public void setSessionId(ServerWebExchange exchange, String id) { 071 Assert.notNull(id, "'id' is required."); 072 exchange.getResponse().getHeaders().set(getHeaderName(), id); 073 } 074 075 @Override 076 public void expireSession(ServerWebExchange exchange) { 077 this.setSessionId(exchange, ""); 078 } 079 080}