WebService authentication via default MembershipProvider - c#

What is the best practice when you need to authenticate specific OperationContracts, while using the default MembershipProvider for security (FormsAuthentication).
I guess that doing Membership.ValidateUser and Membership.GetUser just won't cut it when using WebServices, right?
In other words: How can I verify that a user is allowed to use specific methods in the webservice (that the user is authenticated/"logged on")?

Yeah--you can't really use FormsAuthentication in this case. But there is excellent infrastructure available in WCF for managing role-based access to individual methods: http://msdn.microsoft.com/en-us/magazine/cc948343.aspx

I have been known to over-engineer things, so when I use WCF in my web applications, I wrap the service in my web app. This way my web app calls the abstraction.
Now, what you can do is apply your code access security (CAS) on the wrapper.
Example code might look like this (tons of details omitted for brevity)
internal class ServiceWrapper
{
Service Svc;
public ServiceWrapper()
{
Svc = ServiceClient();
}
[System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Role = "HelloWorld")]
public string HelloWorld()
{
return Svc.HelloWorld();
}
}
In a perfect world, we would want CAS to be a bit more dry (don't repeat yourself), meaning handled in the WCF as you suggest. But this might be a good middle of the road if know you can lock down your WCF app and control who calls it :-)
That would help you simplify getting the ball rolling...
Good luck!

Related

C# webservice and Android app: how prevent illegal accesses

I'm using (with satisfaction) some web services from an Android application.
I use https (I bought a SSL certificate).
I want to prevent unwanted accesses from others that know the urls of my web services.
I use a "secret key" that the app must provide to the web service method, but it's stored in a constant variable inside the code and I know this is not the best solution to ensure security.
Android web service call (using ksoap):
try {
SoapObject request = new SoapObject(configuration.getNamespace(), methodName);
request.addProperty("securityKey", SECURITY_KEY);
C# web service
[WebMethod]
public string UserRegistraion(string securityKey, string data)
{
if (securityKey != Environment.SecurityKey)
{
return "WRONG_KEY";
}
What's the best way to achieve the definitive solution?
EDIT:
As someone suggested, I asked the same question also on security.stackexchange.com
https://security.stackexchange.com/questions/30850/web-services-how-prevent-illegal-accesses
You simply can't do this. You should obfuscate your code. This is an old battle of software developers vs. crackers
You can't block someone on using/analyzing a code that resides on the client-side, but you can make it difficult in a point that almost all people will give up on doing it because it is too much hard to exploit your code.

Caching GET requests with Web API on Azure

I'm developing a Web API RESTful service on the Azure platform.
I thought that the default client-side caching behavior would be to cache GET requests (since GET is idempotent and all).
To my surprise when I deployed the service to Azure all responses were sent with a Cache-Control: private header or other cache-disallowing header.
I tried the solution suggested in this question, it did work locally in IIS but did not work once we deployed to Azure. I could not find anything in the documentation about this ability which I thought was very basic in a RESTful service, I really hope that I'm missing something obvious, in MVC it was very easy.
tl;dr
We need to cache GET requests on the client side when using Azure and Web API.
I don't believe Azure is doing anything to you in this respect. It's a matter of you needing to specify exactly what caching properties you want for your resource(s).
With WebAPI you can control what caching properties your response has via the CacheControlHeaderValue which is accessible via the myHttpResponseMessage.Headers.CacheControl property.
Assuming you had a controller action like this:
public Foo Get(int id)
{
Foo myFoo = LoadSomeFooById(id);
return myFoo;
}
You'll need to do something like this to take control of the caching explicitly:
public HttpResponseMessage Get(int id)
{
Foo myFoo = LoadSomeFooById(id);
HttpResponseMessage myHttpResponseMessage = this.Request.CreateResponse(HttpStatusCode.OK, myFoo)
CacheControlHeaderValue cacheControlHeaderValue = new CacheControlHeaderValue();
cacheControlHeaderValue.Public = true;
cacheControlHeaderValue.MaxAge = TimeSpan.FromMinutes(30);
myHttpResponseMessage.Headers.CacheControl = cacheControlHeaderValue;
return myHttpResponseMessage;
}
Many of the other properties related to caching that you'd expect are also available on the CacheControlHeaderValue class, this is just the most basic example.
Also, bear in mind my example is extremely brute force/simplistic in that all the caching behavior/logic is right there in the action method. A much cleaner implementation might be to have an ActionFilterAttribute which contains all the caching logic based on attribute settings and applies it to the HttpResponseMessage. Then you could revert to the more model centric action method signature because you would, in this case, no longer need access to the HttpResponseMessage anymore at that level. As usual, many ways to skin the cat and you have to determine which works best for your specific problem domain.
Take a look at this http://forums.asp.net/post/4939481.aspx it implements caching as an attribute that modifies the HTTP response.
Disclaimer: I haven't tried it.
I would recommend this https://github.com/filipw/AspNetWebApi-OutputCache
Simple, quick and has various options to cache.
Hope that helps

How can I use web service from Silverlight app?

I am trying to get data form a web service inside a silverlight app. Unfortunately the silverlight app (Bing map app) just hangs when trying to connect.
I use the same code in a console app and it works just fine.
Is there anything special I need to do in silverlight to get it to work? I don't get any exceptions - it just hangs.
I based my service and client code off of this example
http://www.switchonthecode.com/tutorials/wcf-tutorial-basic-interprocess-communication
Problems and Questions:
1. Why can't I set breakpoints in my sliverlight code?
2. How can I successfully call WCF service from a silverlight app? (links to SIMPLE working examples would be great - all the ones I seem to find seem to be quite advanced (RIA, Duplex, etc) Many of these also show xml and other non C# "code" - frankly I don't know what those do and how they relate to the projects, code and services.
(Clearly I am quite ignorant about WCF and silverlight)
As per request for code:
[ServiceContract]
public interface ILGSMapServer
{
[OperationContract]
List<double> GetLatitudes();
}
public class TreeWorkClient
{
ChannelFactory<ILGSMapServer> httpServer;
public ILGSMapServer httpProxy;
public TreeWorkClient()
{
httpServer = new ChannelFactory<ILGSMapServer>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8000/GetLatitudes"));
httpProxy = httpServer.CreateChannel();
}
public List<TreeWorkItem> GetLocations()
{
List<double> lats = httpProxy.GetLatitudes();
//... do stuff in code
return ret;
}
}
I agree with John Saunders - it would be easier to answer this if you published the client code.
However as a guess, a common problem with calling services from Silverlight applications is the restriction Silverlight puts on cross domain calls.
In summary, if your service is at a different domain from the site-of-origin of the Silverlight application, you need to create a client access policy file at the service location.
See this for details:
http://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx
Given your example code you should be seeing the
System.InvalidOperationException: The contract 'ILGSMapServer'
contains synchronous operations, which are not supported in
Silverlight. Split the operations into "Begin" and "End" parts and set
the AsyncPattern property on the OperationContractAttribute to 'true'.
Note that you do not have to make the same change on the server.
You'd need to change your service contract to the following
[ServiceContract]
public interface ILGSMapServer {
[OperationContract( AsyncPattern = true )]
IAsyncResult BeginGetLatitudes( AsyncCallback callback, object context );
List<double> EndGetLatitudes( IAsyncResult result );
}
This also means you'll need to do something completely different in your GetLocations() function as this function will return before the results from the Web have been returned.
Try taking a look at the examples here.
Other options involve using the "Add Service Reference" rather than manually defining it in code.
I believe you need to have this attribute on WCF service for SL to consume it:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
As for debugging - you can debug Silverlight, try using IE for that, its most natural browser for SL debugging (sadly).
Once you start debugging it will be more clear whats wrong when you catch cross domain exception or some other.

.NET webservice client from WSDL

I have a WSDL from which I generated the implementation of ClientBase namely MyService
function void updateData(Data data){
BasicHttpBinding binding = new BasicHttpBinding();
// see there is naked username and password.
EndpointAddress address = new EndpointAddress("http://qa.farwaha.com/eai_enu/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&UserName=john&Password=johspassword");
MyService service = new MyService(binding, address);
try{
service.update(data);
}finally{
service.close();
}
}
Unfortunately, to call this web service I have to pass User name and password as shown in the code. so, my question is around best practices.
Given that its a Winform Application.
How memory / CPU intensive is creating MyService object?
If you suggest cashing the service, it will hold on to the EndpointAddress; which intern has a string with Username and Password. Which is not a good idea .. any work arounds?
If I keep the code as such, service object will be garbage collected .. and there will be no trace of user name or password (as soon as GC runs)
This is a sample code, I have User Object which stores password in SecureString and every time I have to access the password; I get string from SecureString in an instance private method, use it quickly and let it be garbage collected. I believe if I use a method something like above, it will be safe OR safe enough rather than holding on to reference of Service, What do you suggest !!
To your specific questions:
In your client code, what you're constructing are instances of lightweight proxy classes that wrap the channel infrastructure that serialize messages to/from the service's endpoints. As such, these client proxy classes are cheap and fast to construct because they don't generally do a great deal until you actually send something to the service. One thing to watch out for is when you call services which employ a more complex security scheme - establishing connections to such services can be costly and so it's worth caching or re-using such connections if you can.
"Any workarounds"? Nope! Alas, the service you're consuming is poorly designed - not only do they require username and password to be supplied as part of the service method invocation, but they require that you pass them in the clear over HTTP. You might want to ask them to AT LEAST provide an SSL endpoint so that the username and password can be secured during transit. Better still, they could implement basic-auth to allow you to acquire an HTTP auth cookie that you can attach to subsequent calls against their services.
Yes, the GC will eventually clean-up your proxy instances. Better still, you could wrap your instances in using statements to invoke the Dispose pattern and clean-up deterministically. See my Magic8Ball WCF Service on Codeplex for examples.
Other observations:
Because your service requires your username and passoword, each time you call it, you need to pay some very careful thought to how you're going to obtain and store the username and password.
I would urge you to specify your binding information in the app.config rather than inline in your code. Again, see the Magic8Ball WCF Service: If you create bindings in code and the endpoint changes or if they open up a new endpoint, protocol, encoding and/or binding, you'll have to recompile and redist your entire app. If you specify your bindings in config, you might just be able to get away with shipping an updated app.config.
Hope this helps.

c# client calling java axis2 web service, object "resets"

I am very new to web service stuff so please be kind.
I have written a simple POJO class, and deployed it on an axis2 server:
public class Database {
private Project project;
public void login(){
project = new Project();
project.setDescription("Hello there");
project.setName("To me");
}
public Project getProject(){
return project;
}
}
I call the service from a c# client:
localhost.Database db = new WindowsFormsApplication1.localhost.Database();
db.login();
localhost.getProjectResponse pr = new WindowsFormsApplication1.localhost.getProjectResponse();
pr = db.getProject();
When I debug the response is null.
At the java end, when I call getProject, the project object is null.
What's happening?
How do I preserve the state of project between service calls?
For most toolkits, web services are stateless by default. I think axis is no different.
If you want to maintain state between calls then you will need to enable sessions. An example on how to maintain sessions in axis can be found at:
http://kickjava.com/src/test/session/TestSimpleSession.java.htm
On the .NET side you will need to assign a CookieContainer to your request to store the session identifier. See HOW TO: Use CookieContainer to Maintain a State in Web Services for more information.
I think your code would look something like this:
localhost.Database db = new WindowsFormsApplication1.localhost.Database();
// Assign the CookieContainer to the proxy class.
db.CookieContainer = new System.Net.CookieContainer();
db.login();
localhost.getProjectResponse pr = new WindowsFormsApplication1.localhost.getProjectResponse();
pr.CookieContainer = db.CookieContainer;
pr = db.getProject();
I think that should let you do what you want -- but I wouldn't recommend it.
Designing service interfaces is a bit different than designing object oriented interfaces. Service interfaces typically eschew the use of state and instead require the consumer to provide all of the relevant information in the request.
From Service-Oriented Architecture:
Services should be independent,
self-contained requests, which do not
require information or state from one
request to another when implemented.
I would definitely recommend reading that article and perhaps revisiting your design.
I'm not sure why #shivaspk left a comment instead of writing an answer, it is quite correct: web service calls (not just axis calls) are meant to be stateless, so although the project object gets created by
db.login();
when you call
db.getProject();
It is being called on a different instance of your Database class that was created by Axis to service the second call.
There is no really good answer to your question, except for you to rethink what you are trying to do. If you need some kind of authentication (via login), then that authentication needs to be part of every web service call.

Categories