首页 > 解决方案 > 登录重定向后HttpClient无法访问站点

问题描述

我正在尝试在 asp.net core 3.1 应用程序中使用 HttpClient 访问一个站点,该应用程序将我重定向到登录页面(我尝试访问的站点位于登录后面)。

登录页面确实公开了一个身份验证 api(与前端登录页面分开),我首先点击它并使用 cookie 容器。有谁知道我如何才能通过登录页面?这是我正在使用的代码:

  public class ApplicationController : ControllerBase
    {
        private static CookieContainer cookieContainer;
        private static HttpClientHandler clienthandler;
        private HttpClient client;


        public ApplicationController(ILogger<ApplicationController> logger)
        {
        }

        [HttpGet]
        public string GetAsync()
        {
            cookieContainer = new CookieContainer();
            clienthandler = new HttpClientHandler { AllowAutoRedirect = true, 
                     UseCookies = true, CookieContainer = cookieContainer };
            client = new HttpClient(clienthandler);

            HttpContent httpContent = new StringContent("{\"username\": \"account@widget.com\" + 
             ,\"password\": \"Password$6\"}");

            // I can successfully login here and get a 200 back
            HttpResponseMessage response = client.PostAsync("https://widgets.okta.com/api/v1/authn", httpContent).Result;

            // This call redirects to the login page and returns a 200 success, even though it doesn't actually log in nor can I access my website
            var siteResponse = client.PostAsync("https://siteinterestedin.com", httpContent).Result;

标签: asp.net-coreauthenticationredirecthttpclient

解决方案


推荐阅读