Silverlight and ATOM feeds that require authentication - c#

I am building a simple feed reader application that needs to access an ATOM feed that requires authentication. I was going down the route of using the WebClient class and found a Credential property that exists but is not implemented!
webclient.Credentials = new NetworkCredential("username", "password");
Question: What work around are people using for accessing feeds that require basic authentication from a Non-Microsoft site?

You could make a proxy in javascript and have your silverlight controls interface with javascript, which in-turn does the HTTP fetching.
See this for an example: http://weblogs.asp.net/hpreishuber/archive/2009/07/30/silverlight-twitter-client-with-authentication.aspx

Related

UWP client using HttpClient to communicate with .NET Web API, failed connection when SSL is enabled

I'm doing a project where I need to communicate with a Web API from a UWP-application.
I use HttpClient to do the job, and it works fine as long as the Web API is not using SSL. When I turn the SSL on, it just won't work. It works if I use some other client though, like browser/Wpf-application/console-application.
Probably you need to allow unsigned / self signed certificates. If so, you can do it the following way
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
var httpClient = new Windows.Web.Http.HttpClient(filter);
I hope it helps

What is an absolute bare bones httpclient configuration?

I'm coming to .net web api from a JavaScript background, and I'm trying to make a proxy to help with a cross domain JSON request. I'm GETing from a server I don't control the source code for, so I can't configure CORS directly. Likewise, it doesn't speak JSONP.
So two questions as I try to get my head around Web API:
1) Is Httpclient the right tool for this job? (if not, what is?)
2) If httpclient IS the right tool, what is an absolute bare bones httpclient config so I can test this out? Not worried about throwing exceptions or anything else other than just GETing API data and feeding it to a jQuery client.
I guess one other piece of information that would be nice would be building username / password authentication into the http request.
Any help is much appreciated, as are links to any good blogs / tutorials / etc that might help as an introduction to this sort of thing. I've watched several today alone, and I'm still not able to get a basic http request going on the server side without resorting to cutting / pasting other people's code.
Thanks in advance!
** EDIT - To make this question a bit more clear, what I'm trying to test is 1) Can the proxy connect to the third party server, which involves authentication via a username and password 2) Can the proxy then respond to the jQuery client request with the JSON data it received from the third party server.
Thanks to all who have taken the time to respond.
HttpClient seems to be ok in this job.
About the minimal config- it depends on what the third party expects. In most cases would work out-of-the-box, but there always may be some minor tweaks like headers and/or auth code.
I have just found some blog entry where some author shows how to test such a proxy and shows the proxy code too. Please see: http://www.davidbreyer.com/programming/2014/10/11/create-fake-responses-to-rest-service-calls-in-c/
You can find info about sending credentials here: How to use credentials in HttpClient in c#?
HTH
EDIT:
this sample code should work (copied from blog above and modified):
public class Proxy
{
public async Task<ExampleDto> GetExample(int id)
{
var client=new HttpClient();
//set some auth here
//set other headers
var response = client.GetAsync(
string.Format("/api/restserviceexample/{0}", id))
.Result.Content.ReadAsAsync<ExampleDto>();
return await response;
}
}
It's so simple that you can just run it and see if the other server responds. If not, you can play with headers - since all the session info and user auth info are sent using ookies and/or headers, all you have to do is to see how it's made with regular browser and then fake it on the server. Probably best tool for this job will be Fiddler.
However - there is one thing to consider. If the other service has special method for authorization (other than passing credentials with each request) the whole thing becomes tricky, since your proxy should perform authorization using their service, then store their auth cookie on the server or propagate them to the browser and attach them with all next requests.
First, you don't need ASP.NET with C# if you really want minimal.
.NET has great http handling without ASP. Check out classes like HttpListener, HttpListenerContext, HttpListenerRequest, etc... Yes, you'll have to write some boilerplate as your application, but these classes are pretty good.
See among others:
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=599978
Second, if you want user & password, I'd checkout using oauth authentication so you don't have to deal with them directly. Google Plus, Windows Live, Facebook, etc... all have similar OAuth 2.0 APIs for that. See among others:
http://msdn.microsoft.com/en-us/library/dn659750.aspx
https://developers.google.com/+/web/signin/server-side-flow
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2

Implementing session in SOAP Client

I am developing a WP application for which the webservices are implemented in .NET using SOAP client. I have implemented the SOAP client in my WP app using "Add service reference" option.
Now the problem is, there are two different client classes one for the Login functionality and the other for all other queries. Login is working fine and returning me true or false and nothing else. And the other client class is used to make different queries which are all working fine and getting some data from server. After testing I observed that the response is independent of the logged in user( ie server sending same data irrelevant of the logged in user). And hence it is clear that the session is not maintained and the server is sending some anonymous data.
Some one help me on how to maintain the session in the SOAP client.
Note: I cannot ask the web service providers on this. :(
Finally I figured out how to maintain cookie based session in Windows phone apps
Thanks to Mike for his guidance.
For all those who are wondering about the different ways of maintaining session in WP app,
there is a class called CookieContainer which helps to maintain cookie data for us.
Usage:
First create a global instance of CookieContainer class ( I created in App.xaml.cs)
//In App.xaml.cs
CookieContainer cookieContainer = new CookieContainer();
And then assign it to every request we make to the server from our app.
MySoapClient client = new MySoapClient();
client.CookieContainer = (App.Current as App).cookieContainer;
client.LoginAsync("username", "password");
Again for any other request in the app
MyOtherSoapClient anotherClient = new MyOtherSoapClient();
anotherClient.CookieContainer = (App.Current as App).cookieContainer;
anotherClient.PostDataAsync("somedata");
The same rule also applies for normal WebClient and HttpWebRequest classes also.
Happy Coding :)

Using WCF service in MonoTouch with Authentication

I am using a WCF service client generated by slsvcutil form Silverlight toolkit version 4. I've also tried version 3 with the same problems. When I use a client instance running on http with no user credentials it runs without problems. But I need to switch to https for productive servers and send user credentials that are hardcoded for my application. I use the following code for that:
var binding = new BasicHttpBinding (BasicHttpSecurityMode.TransportCredentialOnly);
var endpoint = new EndpointAddress (AppSettings.FlareEndPoint);
_service = new TopicAnalystAPIClient(binding, endpoint);
_service.ClientCredentials.UserName.UserName = "xxx";
_service.ClientCredentials.UserName.Password = "xxx";
When I call a method on that service pointing to http with no authentication it works. When I use the this code against http/https with the credential I get "There was an error on processing web request: Status code 401(Unauthorized): Unauthorized" exception. I've checked that the credentials are correct, I am able to open the service reference in my browser. I've also tried several combinations of http/https and SecurityMode value. I've also tried it on four different servers always with the same result.
What can be the problem?
A lot of permutations are possible. BasicHttpSecurityMode.TransportCredentialOnly should be usable without SSL [1] using HTTP itself. This means the server will send one (or more) authentication method(s) to the client (e.g. basic, digest, ntlm) and Mono (including MonoTouch) should be providing support for the most of them.
It is possible that the linker (if used) removes one of them. In that case you could try building and testing without linking (or skip linking of System.Net.dll).
It's also possible that the authentication method that the serve insist on is not supported. You could find which one is used by running a network trace (e.g. wireshark) or, maybe, it will show up in more details in the server log (along with the 401 error).
[1] http://msdn.microsoft.com/en-us/library/system.servicemodel.basichttpsecuritymode%28v=vs.95%29.aspx

Web service request authentication

We're being really stuck here so I decided to ask your help.
Yesterday I've been asked to help to consume a web service, got the URL to the WSDL, and the user credentials to use.
I've never really had anything to do with web services, but having a general idea about them and seeing a few examples I thought it can't be that bad. Obviously I was wrong as I'm stuck now.
Everything seems to be fine, the proxy class (or client) has been generated, building up requests and sending them are fine too, apart from the authentication part. Which we can't seem to figure out how to do.
Using the:
client.ChannelFactory.Credentials.UserName.UserName = "myusername";
client.ChannelFactory.Credentials.UserName.Password = "mypassword";
doesn't seem to work. (When I check the BindingElementCollection returbed by the client.Endpoint.Binding.CreateBindingElements() there's no SecurityBindingElement)
I've tried so many other ways of doing it, but I think I'm missing something basic and the lack of documentaion is not really helping either.
So the question is: How do I send the username and password when making a call to a web service, using WCF?
Edit:
Just to clarify, the request should contain something similar to this:
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-25763165">
<wsse:Username>username</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">1DiaGTkOLk/CZhDaEpbkAaKRfGw=</wsse:Password>
<wsse:Nonce>6ApOnLn5Aq9KSH46pzzcZA==</wsse:Nonce>
<wsu:Created>2009-05-13T18:59:23.309Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
I had the same problem. Instead of the custom token serializer I used a MessageInspector to add the correct UsernameToken in the BeforeSendRequest method. I then used a custom behavior to apply the fix.
The entire process is documented (with a demo project) in my blog post Supporting the WS-I Basic Profile Password Digest in a WCF client proxy. Alternatively, you can just read the PDF.
If you want to follow my progress through to the solution, you'll find it on StackOverflow titled, "Error in WCF client consuming Axis 2 web service with WS-Security UsernameToken PasswordDigest authentication scheme":
I've achieved similar, using a regular HttpCookie.
To create the cookie:
[OperationContract]
public void LoginToApi(string username, string password, string clientName)
{
// authenticate with DB, if successful ...
// construct a cookie
HttpCookie httpCookie = new HttpCookie("SessionID","whateverneeded");
HttpContext.Current.Response.SetCookie(httpCookie);
}
This appears in your regular HttpRequests, too. So you just reverse the process, checking the hash/session ID/username/password whatever you put in the cookie on receipt before doing anything.
var factory = new ChannelFactory<IService>('*');
factory.Credentials.UserName.UserName = 'bob';
factory.Credentials.UserName.Password = 'bob';
var proxy = factory.CreateChannel();
For more information you can explore Authorization In WCF-Based Services*( http ://msdn.microsoft.com/en-us/magazine/cc948343.aspx)*

Categories