Proxy support for services.AddProtectedWebApi(JWTBearerOptions, MSIdentityOptions.............)
Which Version of Microsoft Identity Web are you using ? Note that to get help, you need to run the latest version.
Where is the issue?
- Web App
- [ ] Sign-in users
- [ ] Sign-in users and call web APIs
- Web API
- [ X] Protected web APIs (Validating tokens)
- [ ] Protected web APIs (Validating scopes)
- [ X] Protected web APIs call downstream web APIs
- Token cache serialization
- [ ] In Memory caches
- [ ] Session caches
- [ ] Distributed caches
Other? - please describe;
Is this a new or existing app?
Repro
I am behind a corporate proxy and need to call WebApi protected by AzureAD from a WebApp protected by AzureAD. Somehow I managed to configure the OpenIdConnect "backchannelhttphandler"options for my WebApp to overcome the 407 proxy issue but now stuck on the API side for validating the tokens received by the WebApp. I am using AddProtectedWebApi method and provided my proxy options in services.AddProtectedWebApi( configureJwtBearerOptions: bearerOptions => { ...................................... options.BackchannelHttpHandler = new HttpClientHandler{.....} }
I also handled the backchannelhttphandler MSIdentityOptions as well but nothing seems to take effect. below is the full error
System.IO.IOException: IDX20807: Unable to retrieve document from: 'https://login.microsoftonline.com/common/discovery/instance?authorization_endpoint=https://login.microsoftonline.com/common/oauth2/v2.0/authorize&api-version=1.1'. HttpResponseMessage: 'StatusCode: 407, ReasonPhrase: 'Proxy Authentication Required', Version: 1.1, Content: System.Net.Http.NoWriteNoSeekStreamContent, Headers: { Cache-Control: no-cache Connection: close Proxy-Connection: close Pragma: no-cache Proxy-Authenticate: NEGOTIATE Proxy-Authenticate: NTLM Proxy-Authenticate: BASIC realm="confidential" Content-Length: 7416 Content-Type: text/html; charset=utf-8 }', HttpResponseMessage.Content: ''. at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel) at Microsoft.Identity.Web.InstanceDiscovery.IssuerConfigurationRetriever.GetConfigurationAsync(String address, IDocumentRetriever retriever, CancellationToken cancel) at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
I am not sure if this is a bug or I am missing something here but wanted to bring this to your attention and seek advice. thank you.
@playground0076 : would you have repro steps on how to setup a proxy? @bgavrilMS @henrik-me @pmaytak @jennyf19 who would be familiar with this scenario?
sure. Below is the proxy code I set up for the webapi.
services.AddProtectedWebApi(
configureJwtBearerOptions: bearerOptions =>
{
bearerOptions.RequireHttpsMetadata = true;
//bearerOptions.MetadataAddress = "https://login.microsoftonline.com/";
// This is a Microsoft identity platform web API.
bearerOptions.Authority += "/v2.0";
bearerOptions.BackchannelHttpHandler = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "myusername",
Domain = "mydomain",
Password = "mypwd"
},
Address = new System.Uri("myproxyurl")
}
};
},
configureMicrosoftIdentityOptions: msIdentityOptions =>
{
msIdentityOptions.RequireHttpsMetadata = true;
//msIdentityOptions.MetadataAddress = "https://login.microsoftonline.com/";
msIdentityOptions.Authority += "/v2.0";
msIdentityOptions.BackchannelHttpHandler = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "myusername",
Domain = "mydomain",
Password = "mypwd"
},
Address = new System.Uri("myproxyurl")
}
};
});
Tried debugging the source code and it failed when retrieving the document (string doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false); in the file IssuerConfigurationRetriever.cs).
public async Task<IssuerMetadata> GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentNullException(nameof(address), $"Azure AD Issuer metadata address url is required");
}
if (retriever == null)
{
throw new ArgumentNullException(nameof(retriever), $"No metadata document retriever is provided");
}
string doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);
return JsonConvert.DeserializeObject<IssuerMetadata>(doc);
}
created a new HttpClient by passing in my proxy credentials and replaced the retriever with this HttpClient and that worked.
var config = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "username",
Domain = "domain",
Password = "password",
},
Address = new System.Uri("myproxyurl"),
}
};
HttpDocumentRetriever testRetriever = new HttpDocumentRetriever(new HttpClient(config));
string doc = await testRetriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);
Can you please advise if this is a bug that needs to be addressed in the library or something I need to handle in my code. thank you.
@playground0076 - In MSAL we solve this problem by allowing developers to use their own HttpClient where they can define the proxy.
In Microsoft.Identity.Web we allow developers to pass in .net core's IHttpClientFactory which scales well.
I believe it should be possible to write an adaptor of IHttpClientFactory that injects your proxy?
@bgavrilMS - hmm, In my webApi's startup classs I am calling .AddProtectedWebApi extension method and it doesn't accept a param for IHttpClientFactory. AddProtectedWebApi method is doing all the magic of adding auth layer, adding httpclient etc from WebApiAuthenticationBuilderExtensions.cs file. And as it's a WebApi, I dont think there is any logic related token acquisition in there.
can you clarify from where I can pass in the IHttpClientFactory adaptor?
@jennyf19 and @jmprieur can help, I am not that well familiar with Identity.Web's API. The point I'm trying to make is that you need to have access to the HttpClient used in order to configure a proxy.
@playground0076 : you don't need to have a parameter in AddProtectedWebAPI
I believe that you just need to provide your own implementation of IHttpClientFactory , and add it as a service before calling AddProtectedWebApi https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
@jmprieur Thank you for responding. I tried a variety of ways but nothing seems to work.
WebApi Startup.cs
var config = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "myusername",
Domain = "mydomain",
Password = "mypassword",
},
Address = new System.Uri("myproxyurl"),
}
};
services.AddHttpClient("something").ConfigurePrimaryHttpMessageHandler(()=> config);
var builder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddProtectedWebApi(options =>
{
Configuration.Bind(sectionName, options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => Configuration.Bind(sectionName, options));
services.AddControllers();
But no matter what I try, I see the httpclient property as null in the retriever object.
public async Task<IssuerMetadata> GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentNullException(nameof(address), $"Azure AD Issuer metadata address url is required");
}
if (retriever == null)
{
throw new ArgumentNullException(nameof(retriever), $"No metadata document retriever is provided");
}
string doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);
return JsonConvert.DeserializeObject<IssuerMetadata>(doc);
}
I am actually a .net classic guy and don't have too much knowledge with .net core but tried my level to make this work. If you believe this is not a bug with the library and more of a coding issue, feel free to close the issue and I will look for solutions in stackoverflow. Thank you.
@playground0076 : please look at this article, which should help your make this scenario work https://github.com/AzureAD/microsoft-identity-web/wiki/Deploying-Web-apps-to-App-services-as-Linux-containers
@playground0076 did you find a solution for your problem and could you share it? I have looked at the Forwarded Headers solution, but can't get it to work. I need to set the proxy url and port, can not use os default. thanks