Why is accessing session through HttpContext.Current bad [practice]? - session-variables

I am trying out signalR and followed their Chat sample with a few modifications. So, in the ChatHub.cs, I tried to access the user's session variable and found out that I couldn't. So I've searched the web for answers and found this: Access to Session from a Hub
So as commented by Mr. David Fowl, accessing session variables through HttpContext.Current is bad. Is it really that bad that I should avoid using it? I really need to access the session variable.

I am guessing the reason it is bad is because your code will not work if hosted outside of the asp.net context. Since HttpContext.Current is web specific

Related

Sending Emails as Scoped Vs. Transient in ASP.NET Core

I'm wondering... why does Microsoft use this:
services.AddTransient<IEmailSender, AuthMessageSender>();
In their tutorials for sending e-mails in ASP.NET Core rather than:
services.AddSingleton<IEmailSender, AuthMessageSender>();
Isn't the service supposed to stay the same for the lifetime of the project?
What is the downside of this?
Thanks :)
The reason why they use Transient its because their example is based on Forgot Password.
Forgot password is something secundary it doesnt do part of the main app logic, so it is cheaper in terms of resources to create the service once you need it and after use, discard it. This is the reason they use Transient.
If its a singleton it will be always in memory once it is created and for the forgot passward case which is rare to happens, it is not worth it.

SecurityContext.Current not working, nullexception

im using a WCF service with the users and roles being kept in the database. In my service im trying to identify whose calling the service. So i type in my WCF service
string user = ServiceSecurityContext.Current.PrimaryIdentity.Name;
but i get i nullexception object not sent to an reference, ive tried googleing it all day but cant seem to find whats wrong. Any suggestions ?
"What's wrong" is that ServiceSecurityContext.Current is returning null rather than an instance of ServiceSecurityContext.
One scenario where this occurs is if the binding is configured to use Message security with MessageCredentialType set to None.
However, I'm not aware of any comprehensive documentation listing every scenario where ServiceSecurityContext.Current can be null: as the security context is established in the channel stack it is something which depends on the specific binding configuration and security providers in use. It could also, I imagine, be affected by custom Behaviors which fiddle with message properties.
Having said that, unless you have custom code inserted into the channel stack, it is probably a safe assumption that this will only occur in cases where the binding does not require any client authentication. You should check first of all that you are using a binding configuration which will auhenticate the client and provide the kind of user name IIdentity you are expecting.

WCF security with Domain Groups

I have a WCF service which I would like to secure with windows domain groups. I do not want to include the PrincipalPermission attibute in the code!
I would like to call the services from a web application using the application pool identity. This identity would be checked to ensure that it is a member of the domain group securing the WCF service. All of this would be defined in config. This seems like a really neat solution, except ..... defining the domain group as securing the WCF service does not seem possible. Anyone got any ideas how I might do this.
I am using netTCPBinding (or named pipes but prefer the netTCP) and hosting the service in IIS within windows 2008.
As per my understanding , you want to use imperative checking than declarative checking at design time.
If thats the case you can replace the declaration with an imperative checing in the method body like
PrincipalPermission checkPerminssions = new PrincipalPermission(
null, #"DomainName\WindowsGroup");
checkPerminssions .Demand();
You can also use IsInRole method using IPrincipal Interface.
However you can find more information at Authorization
I would love to know why you want to do that.
Hope this helps.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

WCF, Custom Membership Provider and HttpContext

Ok, Im really going to show my stupidity regarding the ASP.NET security model here but here goes.
I have a WCF web service and I have managed to hack my way around to having it pipe through my custom membership provider.
My membership provider overrides "ValidateUser" in which I attempt to load a user object with data from our SQL server instance. All good so far, I retrieve the creds, load the users object and return true if I don't hit any bumps in the road.
At this point, I would usually stuff the user object (or id) into session or actually just some state bag that's accessible for the lifetime of the request. The problem that I am hitting is that HttpContext is null at this point, even though Im using ASP compatability attributes.
What other options do I have at hand?
Cheers, Chris.
EDIT:
Just to clarify what I want to do. I want to pass user credentials to be authenticated on the server, and once this has happened I would like to keep the the details of the authenticated user somewhere that I can access for the lifetime of the service request only. This would be the equiv of Http.Current.Items?
Is there any object that is instantiated per-request that I can access globally via a static property (i.e. in a similar way to HttpContext.Current)? I assumed that OperationContext was the this, but this is also null?
Can this really be such an uncommon problem? Send creds > retrieve user > stuff user somewhere for access throughout processing the request. Seems pretty common to me, what am I missing?
Cheers, Chris.
Basically, with WCF, the preferred best practice solution is to use per-call activation, e.g. each new request / call gets a new instance of the service class, and all the necessary steps like authentication and authorization are done for each request.
This may sound inefficient, but web apps, and in particular web services, ought to be totally stateless whenever possible. Putting stuff in a "state bag" just calls for problems further down the road - how do you know when to invalidate that cached copy of the credentials? What if the user exists your app but the cookie stays on his machine?
All in all, I would strongly suggest trying to get used to the idea of doing these step each and every time. Yes, it costs a little bit of processing time - but on the other hand, you can save yourself from a lot of grief in terms of state management in an inherently stateless environment - always a kludge, no matter how you look at it....
If you still insist on that kludge, you can turn on an ASP.NET "compabitility" mode for WCF which should give you access to HttpContext - but again: I would strongly recommend against it. The first and most obvious limitation is that this ASP.NET compatibility mode of course only works when hosting your WCF service in IIS - which I would again rather not do in production code myself.
To turn on the ASP.NET compatibility mode, use this setting in web.config:
<system.serviceModel>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
and you need to decorate your service implementation (the class implementing the service contract) with a corresponding attribute:
[AspNetCompatibilityRequirements(RequirementsMode=
AspNetCompatibilityRequirementsMode.Allowed)]
class YourService : IYourService
The AspNetCompatibilityRequirementsMode can be NotAllowed, Allowed or Required.
For more information and a more thorough explanation, see Wenlong Dong's blog post on ASP.NET Compatibility Mode