@@ -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.
@@ -235,7 +237,12 @@ private static AadInstanceDiscoveryResponse sendInstanceDiscoveryRequest(URL aut
235237 httpResponse = executeRequest (instanceDiscoveryRequestUrl , msalRequest .headers ().getReadonlyHeaderMap (), msalRequest , serviceBundle );
236238
237239 if (httpResponse .statusCode () != HttpHelper .HTTP_STATUS_200 ) {
238- throw MsalServiceExceptionFactory .fromHttpResponse (httpResponse );
240+ if (httpResponse .statusCode () == HttpHelper .HTTP_STATUS_400 && httpResponse .body ().equals ("invalid_instance" )){
241+ // instance discovery failed due to an invalid authority, throw an exception.
242+ throw MsalServiceExceptionFactory .fromHttpResponse (httpResponse );
243+ }
244+ // instance discovery failed due to reasons other than an invalid authority, do not perform instance discovery again in this environment.
245+ instanceDiscoveryFailed = true ;
239246 }
240247
241248
0 commit comments