简体   繁体   中英

How to make an external GET request from IIS hosted WebAPI/MVC app (via proxy server)

We use Windows authentication . I've created both WebAPI / MVC applications to play with.

When hosted on production server / IIS appplication requires credentials to perform HTTP GET to an external site. For some reasons we temporarily cannot use special AD account for that.

I've read about ASP.NET impersonation . As far as I understand it is possible to incorporate with caller's credentials? I've tried to use this code though I'm not sure whether it is an appropriate approach to use with WebAPI .

[HttpGet]
[Route("api/test")]
public HttpResponseMessage test() {
    using(var ctx = WindowsIdentity.GetCurrent().Impersonate()) {
        var proxyOptions = new WebProxy("[proxyUrl]");
            proxyOptions.UseDefaultCredentials = true;

        var client = new WebClient();
            client.UseDefaultCredentials = true;                
            client.Proxy = proxyOptions;

        return new HttpResponseMessage {
            Content = new StringContent(
                content: client.DownloadString("[externalApiUrl]"),
                encoding: Encoding.Default,
                mediaType: "text/plain"
            )
        };
    }
}

Anyway this doesn't work.

Should I configure delegation instead of impersonation ?

How to perform an external request without a separate AD account for that?

Have you tried explicitly setting the credentials using

var proxyConfig = new WebProxy(
proxyServerUrl, 
BypassOnLocal: false, 
BypassList: null, 
Credentials: new NetworkCredential(username, password)
);

The username / password should be an authorized user on your proxy server. Since you are using Windows Authentication, you may need to prefix domain name in the username Eg domain\\username

This approach should work in all the 3 environments you have mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM