WebView Source - Automatic Authentication

I am looking for a way to automatically authenticate for a website. I have a WebView in my Windows C # storage application and I want to access a password protected site.

WebView.Source= new URI("http://UserId: Password@foo.com /"); 

This does not work as I get a security exception:

 A security problem occurred. (Exception from HRESULT: 0x800C000E); 

The method below also does not work, since I get only the html of the site, but not css or JavaScript:

 HttpClientHandler handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("UserId", "Password"); HttpClient client = new HttpClient(handler); string body = await client.GetStringAsync("http://foo.com"); webview.NavigateToString(body); 

Is there another way?

+4
source share
1 answer

I ran into the same problem, but fortunately I found the answer :) The main problem here is that Windows storage applications contain 2 different HttpClient files

One of them is the "classic" that we know from C # applications (used automatically), and the other is the "new" HttpClient - which is associated with WebView :)

Anthers - both types:

System.Net.Http.HttpClient (classic)
Windows.Web.Http.HttpClient (new)

So, don't forget to announce the new One and do something like the following code

 var filter = new HttpBaseProtocolFilter(); filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential("http://website","login", "password"); Windows.Web.Http.HttpClient client2 = new Windows.Web.Http.HttpClient(filter); var response = await client2.GetAsync(new Uri("http://website")); WebView.Source = new Uri("http://website"); 

Now remember to change the username and password to the credentials you want to use, and the website is the site you want to authenticate to.

It is important to get a response from the server - this will make the authenticated server @ server, so the next time you go to this site with a web browser, you will be authenticated

It works great with basic authentication and NTLM authentication

Hope this helps people find a solution to this problem :)

+5
source

Source: https://habr.com/ru/post/1493377/


All Articles