c# – WebClient DownloadFile with Authorization not working – Stack Overflow

Access an oauth 2.0 third-party resource with spring webclient

For the WebClient to handle the GitHub grant flow, it must include the ServerOAuth2AuthorizedClientExchangeFilterFunction filter. Create the package com.okta.developer.search.configuration and add the class WebClientConfiguration:

The ServerOAuth2AuthorizedClientExchangeFilterFunction provides a mechanism for using an OAuth2AuthorizedClient to make requests including a Bearer Token, and supports the following features:

Create a secure microservice with okta authentication

Start by building a simple microservice that returns the total count of a GitHub code search by keyword. The third-party service in this example is GitHub REST API.

Forms aвторизация через модифицированный webclient с куками

Доброго дня. Есть сайт первый и второй.
Нужно получить доступ к защищенному методу в первом, используя стандартный механизм авторизации форм.
WebClient на втором сайте делает запрос на авторизацию, отсылая имя/пароль, ему приходит кука, он ее сохраняет и посылает второй запрос на защищенный метод с кукой.
Во втором запросе видна AUTH кука и она валидна, но авторизация не проходит.

Request.isauthenticated = false

В чем может быть дело?

Код запросов вебклиента

    //Create an instance of your new CookieAware Web Client
var client = new CookieAwareWebClient();

//Authenticate (username and password can be either hard-coded or pulled from a settings area)
var values = new NameValueCollection { { "Name", "name" }, { "Password", "1234" } };

//Perform authentication - after this has been performed the cookie will be stored within the Web Client
client.UploadValues(new Uri("http://localhost:15536/Plugins/ProductListGetter/login"), "POST", values);
var _cookies = client.ResponseHeaders["Set-Cookie"];

client.UploadString(new Uri("http://localhost:15536/Plugins/ProductListGetter/ChangeNameForCurrentUser"), "POST", "Example Message");
client.UploadString(new Uri("http://localhost:15536/Plugins/ProductListGetter/ChangeNameForCurrentUser"), "POST", "Example Message");
client.Dispose();

Код модифицированного вебклиента для поддержки кук

public class CookieAwareWebClient : WebClient
{
    //Properties to handle implementing a timeout
    private int? _timeout = null;
    public int? Timeout
    {
        get
        {
            return _timeout;
        }
        set
        {
            _timeout = value;
        }
    }

    //A CookieContainer class to house the Cookie once it is contained within one of the Requests
    public CookieContainer CookieContainer { get; private set; }

    //Constructor
    public CookieAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }

    //Method to handle setting the optional timeout (in milliseconds)
    public void SetTimeout(int timeout)
    {
        _timeout = timeout;
    }

    //This handles using and storing the Cookie information as well as managing the Request timeout
    protected override WebRequest GetWebRequest(Uri address)
    {
        //Handles the CookieContainer
        var request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = CookieContainer;
        //Sets the Timeout if it exists
        if (_timeout.HasValue)
        {
            request.Timeout = _timeout.Value;
        }
        return request;
    }

Important new observations

That last one is a biggie. I find myself in a situation where I can get my config to save with a WebClient post, but I have to ignore a 401 response in order to do so. Obviously, this is far from ideal. So close, yet so far!

Похожее:  Госуслуги: возможности личного кабинета, типы учетных записей

Learn more about reactive spring boot and webclient

I hope you enjoyed this tutorial and got a clear picture of WebClient testing for applications that access third-party services. As mentioned before, WebClient and WebTestClient documentation pieces are covered in the three references, Spring Framework, Spring Boot, and Spring Security, so I recommend taking a thorough look at all of them.

An additional aspect to explore is how to add layering, given that client registrations must be injected as controller parameters, to trigger the authorization flows when required. Keep learning about Reactive Applications with Spring Boot, and OAuth security, and check out the following links:

You can find the application code on GitHub in the okta-spring-webclient-example repository.

Webclient downloadfile with authorization not working

I have tried just about everything I can think of to get this to work, including several things I’ve found online. All I’m trying to do is download a file (which has a direct link) from a website that I have to log in to.

I tried doing the following, with the “UploadValues”:

WebClient myWebClient = new WebClient();
NameValueCollection myNameValueCollection = new NameValueCollection();
myNameValueCollection.Add("username", this.UserName);
myNameValueCollection.Add("password", this.Password);
byte[] responseArray = myWebClient.UploadValues(felony, myNameValueCollection);
myWebClient.DownloadFile(felony, localfelony);

and I’ve also tried putting the login info in the headers as well. I’ve also tried just setting the credentials, as you can see from the commented code:

WebClient client = new WebClient();
//client.UseDefaultCredentials = false;
//client.Credentials = new NetworkCredential(this.UserName, this.Password);
client.Headers.Add(HttpRequestHeader.Authorization, "Basic "   Convert.ToBase64String(Encoding.ASCII.GetBytes(this.UserName   ":"   this.Password)));
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
//client.Headers.Add(HttpRequestHeader.Cookie, this.webBrowser.Document.Cookie);
client.DownloadFile(felony, localfelony);

No matter what I try, the only thing I can get it to download is a file that ends up being the login page, as if it didn’t accept the login info I passed.

Похожее:  Отдельная страница авторизации для DLE » Бесплатно dle шаблоны, dle модули и скрипты

I’ve looked at the headers and such, and I don’t see anything out of the ordinary that would explain why this isn’t working. Any ideas?

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 4,00 из 5)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector