我想使用Azure应用程序代理从WebAPI访问OnPrem WebService。由于Passthrough不是一个好主意,并且AAP不支持托管身份,因此我们仅限于预身份验证。
WebAPI已经具有用户上下文,因为我们需要委派权限。 用户被分配给Proxy-App,WebAPI也有权访问它。但是,当我调用外部url(不是signin-url,而是return-url)时,我们仍然具有访问Proxy-App的令牌,但我获得了signin-page的源代码,而不是来自测试站点的源代码。我正在挖洞。但是,使用浏览器时,它可以工作。使用PASSTHROUGH也可以,但是不需要。
public class ApplicationProxyhandler : HttpClientHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var token = GetToken($"{request.RequestUri.Scheme}://{request.RequestUri.Authority}");
request.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
return base.SendAsync(request, cancellationToken);
}
public static AdalToken GetToken(string resource)
{
HttpClient client = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/***/oauth2/token";
var body = $"resource={resource}&client_id={AppId}&grant_type=password&username={UserName}&password={Password}&scope=user_impersonation";
var stringContent = new StringContent(body, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
var result =
client.PostAsync(tokenEndpoint, stringContent)
.ContinueWith<string>((response) => response.Result.Content.ReadAsStringAsync().Result).Result;
return JsonConvert.DeserializeObject<AdalToken>(result);
}
}
这样使用代码
using (HttpClient hc = new HttpClient(new ApplicationProxyhandler()))
{
var str = await hc.GetStringAsync("https://mytestsite-msapproxy.net");
}