WCF Check if the request was made securely - c#

Baisicly the thing I wanna do is find out if the request to my wcf service was made securely. And I use the following code.
context = OperationContext.Current;
bool isSecure = context.IncomingMessageHeaders.To.Scheme == Uri.UriSchemeHttps;
is this a proper way to do that ? If you don't understand what I mean and what I want to achieve I can provide more details.

You can check Request.IsSecureConnection
See MSDN documentation

I guess you want to check because you are going to execute different logic depending on whether the connection was secure or not.
In this case, I would take a different approach. Rather than check in the service code and switch the control flow, you could consider implementing the different logical flows in different endpoint behaviors - configure one one for the HTTP endpoint and the other for HTTPS endpoint.
This feels like better encapsulation that the approach of checking the operation context and would likely be more testable.

Related

Get original origin of request with .NET Core API

I know that Request.Headers["Origin"] gets the origin header of a request, but this is changeable on the client-side by setting the header manually. Thus not that safe.
Is there such a value that contains the original, readonly/unchangeable origin of a request? Like the one CORS is using?
I need this value to check if the request is officially coming from the site it's supposed to come from. The trick is that I need it in the controller method to search an object in the database based on this value and a key only used for that site.
The problem with CORS is that it can whitelist a list of URLs but not check if the site and the key belong to each other, thus can whitelisted site 1 access the data of whitelisted site 2 if it mimics the Request.Headers["Origin"] and the key of site 2
Unfortunately (or perhaps fortunately?) there is no reliable way to check this from the data that the browser sends to your server. The user is able to forge any and all information that you receive from the browser.
This is why mechanisms that need to reliably determine the origin of a user use some sort of token mechanism, public/private signatures, certificates and the sort to determine it. Unfortunately this is never as simple as looking up some information that the browser provides you with, so it seems like you might need to redesign your whitelisting mechanism by relying on something else than origin, possibly implicating single-sign-on measures (like SAML). It's hard to provide further suggestions without more information on the underlying problem that the origin-check is intended to solve.

Web api performance?

I was thinking ,
The WebApi along with routing mechanism works in such way that it reads the http verb ( GET POST etc...) and then searches for matched method names / parameters :
For example :
If it's GET and the URI is api/Customers/5:
method should start with Get
if it has ID so search a method which accepts int as parameter.
etc. (there are more rules).
I mostly believe they did it using reflection.
Question :
Isn't it a performance hit , for every URI request - to search all this data just to attach a method ?
Where I could easily send a very short string from a client which will imply on the method on the server side ?
Why not doing it the simple way ? Ok cause we want to use http verbs as meaning. OK. but so much operations just to execute a method
example #1
get api/Customers/5
could be
a.ashx?m=gc&id=5 (method=GetCustomer & id=5)
example #2
put api/Customers/5?v=123
could be
a.ashx?m=uc&id=5?v=123' (method=UpdateCustomer & id=5 & value=123)
mine is even shorter.
Dont get me wrong. I believe this api was done by very smart people who knew what they talk about.
Just want o know what am I missing.
Web api has a lot of options that you don't have with HTTP Handler if you don't code it
Full list: http://www.asp.net/whitepapers/mvc4-release-notes#_Toc317096197
OData support (via Queryable attribute)
Content Negotiation
Filters
Model binding and validation
Ability to self host outside of IIS
Link generation to related resources that incorporates routing rules
Full support for routes/routing
Ability to create custom help and test pages using IApiExplorer
Performance comparison HttpHandler vs WebAPI: http://www.west-wind.com/weblog/posts/2012/Sep/04/ASPNET-Frameworks-and-Raw-Throughput-Performance
As always, you need to choose the the technology that suits you best, if you want performance go with Http Handler. If you want flexibility and rest go with Web API. You might want rest if you expose web services that other will consume

User Authorization in WCF with BasicHttpBinding with TransportWithMessageCredential

I currently have a service which is secured by TransportWithMessageCredential over https. This works great! I now need to add a bit of granularity to some operations on this service.
Lets say I have this method public IEnumerable<Project> GetProjects() now I need to add an additional method which will limit the projection to projects which the current user has access.
Is using code like this:
var uid = System
.ServiceModel
.OperationContext
.Current
.IncomingMessageProperties
.Security
.ServiceSecurityContext
.PrimaryIdentity;
var returnProjects = context.Projects.Where(p => p.ProjectManager.Equals(uid.Name));
going to leave me vulnerable to any type of attack?
I think this should be fine, since WCF will hit my custom UserNamePasswordValidator first and "authenticate" the user, then the code I have above will "authorize" them to get only their projects. Is there a flaw in my thinking here?
No, that is perfectly valid thinking. This is exactly the way that we implement user-specific security (with the minor exception that we use FormsAuthentication for identifying the user).
Before each request is processed, we always check the user and if there is anything suspicious about the request, we throw an exception.

How do I securely authenticate the calling assembly of a WCF service method?

The current situation is as follows:
We have an production .net 3.5 WCF service, used by several applications throughout the organization, over wsHttpBinding or netTcpBinding. User authentication is being done on the Transport level, using Windows integrated security. This service has a method Foo(string parameter), which can only be called by members of given AD groups. The string parameter is obligatory.
A new client application has come into play (.net 3.5, C# console app), which eliminates the necessity of the string parameter. However, only calls from this particular application should be allowed to omit the string parameter. The identity of the caller of the client application should still be known by the server because the AD group limitation still applies (ruling out impersonation on the client side).
I found a way to pass on the "evidence" of the calling (strong-named) assembly in the message headers, but this method is clearly not secure because the "evidence" can easily be spoofed.
Also, CAS (code access security) seems like a possible solution, but I can't seem to figure out how to make use of CAS in this particular scenario.
Does anyone have a suggestion on how to solve this issue?
Edit: I found another thread on this subject; apparently the conclusion there is that it is simply impossible to implement in a secure fashion.
sounds to me like you need to pull the security out into a seperate service ... go down a more federated route this way you can implement a handshake form of encryption using public and private keys to generate a secure session token in both situations.
this way you cna still get both windows a=uthentication and a custom solution in play whilst retaining your attributes on methods for security (I am assuming that you are implementing it this way.)
sounds like a fair bit of work though - I had to do this from scratch and ran into some cross domain / delegation issues. But I am sure the idea is good.
howver you will end up with a nice solid claims based secuirty model
You could get the callers Address:
RemoteEndpointMessageProperty clientAddress =
OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]
as RemoteEndpointMessageProperty;
string address = clientAddress.Address;

Global variables in WCF REST services

My applciation works as follows
[user]----username/password/domain----->[WCF service]
then i access the domain server to see to which actual DB the user is associated,
after getting that, i validate the user in his actual DB(DB is per domain)
the problem is that i need a place to store the domain name for the following requests against the db.
for example,if the users calls a WCF service operation:
Test()
first the validation procedure is called, (WCF UserNamePasswordValidator) which validates the user password(which is sent as part of the header for REST or as part of the SOAP), and the next function to be called is the Test, but by then i cant tell the domain of the user(to actually serve the request agains that domain..)
I dont want to change the signature of each domain to
Test(string domain)
I cant simply access the headers since i expose the same methods both as REST and as SOAP and the authentication is different for each of them..(one is with headers as with Amazon S3 and the later is using the SOAP standard)
so basically i'm looking for a global, per call storage.(i want to avoid the Per-Call initiation method)
thanks.
EDIT:
Maybe i should use the ThreadStaticAttribute? will that work?
This will not work. You can't store anything in UserNamePasswordValidator. It even doesn't have access to OperationContext because it runs on different thread.
The way to do this is create custom message inspector and extract the information from custom message header to custom operation context extension as Frank mentioned.
WCF knows a Current OperationContext. You can write your own extensions for it. Unrelated to this issue, I used the same mechanics in this NHibernate Session management here, which may work in its concept for you as well. It accesses the InstanceContext, but the concepts are similar.

Categories

Resources