@@ -38,6 +38,8 @@ class AadInstanceDiscoveryProvider {
3838
3939 private static final Logger log = LoggerFactory .getLogger (AadInstanceDiscoveryProvider .class );
4040
41+ //flag to check if instance discovery has failed
42+ private static boolean instanceDiscoveryFailed = false ;
4143 static ConcurrentHashMap <String , InstanceDiscoveryMetadataEntry > cache = new ConcurrentHashMap <>();
4244
4345 static {
@@ -84,7 +86,7 @@ static InstanceDiscoveryMetadataEntry getMetadataEntry(URL authorityUrl,
8486 InstanceDiscoveryMetadataEntry result = cache .get (host );
8587
8688 if (result == null ) {
87- if (msalRequest .application ().instanceDiscovery ()){
89+ if (msalRequest .application ().instanceDiscovery () && ! instanceDiscoveryFailed ){
8890 doInstanceDiscoveryAndCache (authorityUrl , validateAuthority , msalRequest , serviceBundle );
8991 } else {
9092 // instanceDiscovery flag is set to False. Do not perform instanceDiscovery.
@@ -234,12 +236,18 @@ private static AadInstanceDiscoveryResponse sendInstanceDiscoveryRequest(URL aut
234236
235237 httpResponse = executeRequest (instanceDiscoveryRequestUrl , msalRequest .headers ().getReadonlyHeaderMap (), msalRequest , serviceBundle );
236238
239+ AadInstanceDiscoveryResponse response = JsonHelper .convertJsonToObject (httpResponse .body (), AadInstanceDiscoveryResponse .class );
240+
237241 if (httpResponse .statusCode () != HttpHelper .HTTP_STATUS_200 ) {
238- throw MsalServiceExceptionFactory .fromHttpResponse (httpResponse );
242+ if (httpResponse .statusCode () == HttpHelper .HTTP_STATUS_400 && response .error ().equals ("invalid_instance" )){
243+ // instance discovery failed due to an invalid authority, throw an exception.
244+ throw MsalServiceExceptionFactory .fromHttpResponse (httpResponse );
245+ }
246+ // instance discovery failed due to reasons other than an invalid authority, do not perform instance discovery again in this environment.
247+ instanceDiscoveryFailed = true ;
239248 }
240249
241-
242- return JsonHelper .convertJsonToObject (httpResponse .body (), AadInstanceDiscoveryResponse .class );
250+ return response ;
243251 }
244252
245253 private static int determineRegionOutcome (String detectedRegion , String providedRegion , boolean autoDetect ) {
0 commit comments