2323
2424package microsoft .exchange .webservices .data ;
2525
26+ import org .apache .http .client .CookieStore ;
2627import org .apache .http .client .protocol .HttpClientContext ;
2728import org .apache .http .config .Registry ;
2829import org .apache .http .config .RegistryBuilder ;
2930import org .apache .http .conn .HttpClientConnectionManager ;
3031import org .apache .http .conn .socket .ConnectionSocketFactory ;
3132import org .apache .http .conn .socket .PlainConnectionSocketFactory ;
33+ import org .apache .http .impl .client .BasicCookieStore ;
3234import org .apache .http .impl .client .CloseableHttpClient ;
3335import org .apache .http .impl .client .HttpClientBuilder ;
3436import org .apache .http .impl .client .HttpClients ;
@@ -131,7 +133,7 @@ public abstract class ExchangeServiceBase implements Closeable {
131133
132134 protected CloseableHttpClient httpClient ;
133135
134- protected HttpClientContext httpContext = HttpClientContext . create () ;
136+ protected HttpClientContext httpContext ;
135137
136138 protected HttpClientWebRequest request = null ;
137139
@@ -151,6 +153,7 @@ public abstract class ExchangeServiceBase implements Closeable {
151153 protected ExchangeServiceBase () {
152154 setUseDefaultCredentials (true );
153155 initializeHttpClient ();
156+ initializeHttpContext ();
154157 }
155158
156159 protected ExchangeServiceBase (ExchangeVersion requestedServerVersion ) {
@@ -195,7 +198,17 @@ private void initializeHttpClient() {
195198 httpClient = httpClientBuilder .build ();
196199 }
197200
198- @ Override
201+ /**
202+ * (Re)initializes the HttpContext object. This removes any existing state (mainly cookies). Use an own
203+ * cookie store, instead of the httpClient's global store, so cookies get reset on reinitialization
204+ */
205+ private void initializeHttpContext () {
206+ CookieStore cookieStore = new BasicCookieStore ();
207+ httpContext = HttpClientContext .create ();
208+ httpContext .setCookieStore (cookieStore );
209+ }
210+
211+ @ Override
199212 public void close () {
200213 try {
201214 httpClient .close ();
@@ -579,6 +592,9 @@ public ExchangeCredentials getCredentials() {
579592 public void setCredentials (ExchangeCredentials credentials ) {
580593 this .credentials = credentials ;
581594 this .useDefaultCredentials = false ;
595+
596+ // Reset the httpContext, to remove any existing authentication cookies from subsequent requests
597+ initializeHttpContext ();
582598 }
583599
584600 /**
@@ -605,8 +621,11 @@ public void setUseDefaultCredentials(boolean value) {
605621 if (value ) {
606622 this .credentials = null ;
607623 }
608- }
609624
625+ // Reset the httpContext, to remove any existing authentication cookies from subsequent requests
626+ initializeHttpContext ();
627+ }
628+
610629 /**
611630 * Gets the timeout used when sending HTTP requests and when receiving HTTP
612631 * responses, in milliseconds.
0 commit comments