Is a SecurityContext shared between requests when using Spring Security? - authentication

I'm seeing some strange behaviour when using stateless token-based authentication on a rest API written using Spring Boot.
The client includes a JWT token with each request, and a custom filter I've written that extends GenericFilterBean adds an Authentication object based on the claims in the token to the security context using the following :
SecurityContextHolder.getContext().setAuthentication(authentication);
And clears the context after processing the request by doing :
SecurityContextHolder.getContext().setAuthentication(null);
However when the simple app I've developed performs a range of operations, I sometimes see that the security context isn't being set correctly - sometimes it's null for a request that has supplied a token. The filter is being called correctly, setAuthencation() is also being called, but the request fails authentication, and throws a 403 denied.
If I explicitly turn off any http Session management by setting the session creation policy to STATELESS, this behaviour stops.
Any ideas what could be happening here? Is the security context being shared between threads dealing with requests in some way?

It seems that the context can be shared, according the official documentation here :
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
In an application which receives concurrent requests in a single session, the same SecurityContext instance will be shared between threads. Even though a ThreadLocal is being used, it is the same instance that is retrieved from the HttpSession for each thread. This has implications if you wish to temporarily change the context under which a thread is running. If you just use SecurityContextHolder.getContext(), and call setAuthentication(anAuthentication) on the returned context object, then the Authentication object will change in all concurrent threads which share the same SecurityContext instance. You can customize the behaviour of SecurityContextPersistenceFilter to create a completely new SecurityContext for each request, preventing changes in one thread from affecting another. Alternatively you can create a new instance just at the point where you temporarily change the context. The method SecurityContextHolder.createEmptyContext() always returns a new context instance.

Related

correct pattern of Ktor's HttpClient usage

What's the correct pattern of usage for HttpClient in KTOR. Should I use it like singleton per app lifecycle, or should I create it per each request?
I would say that you may have more than one client per app if you need to connect to more than one logical services.
But if you are dealing with one single HTTP server it's better to have one client because it establishes and holds a connection with server. It also allocates the following resources: prepared threads, coroutines and connections. If you have multiple clients you can potentially run out of these resources.
Should I use it like singleton per app lifecycle, or should I create it per each request
Creation of a http client instance is usually a bit resource intensive, hence you should not create an instance of client for every request. You should create just one http client instance per app's lifecycle, injected wherever required in your app, ensuring that
you have used the right http client configurations like the thread pool size, timeouts etc
you are releasing the resources upon the app's shutdown.
The client can be configured with HttpClientEngineConfig(doc) or any of its inheritors. More details in the documentation here.
It is better to reuse the HttpClient instance for performance reasons if the requests can be performed using the same configuration/settings.
But in some cases you have to create separate instances because the features of a HttpClient are determined by the engine and the plugins specified when creating the instance.
For example when using bearer authentication the HttpClient instances can be reused only when sending requests to the same resource server (with the same authorization configuration).
Similarly, if two requests should use different timeouts then they can be performed only by different HttpClients.
To summarize, a HttpClient instance should be created per "feature set", determined by the required engine and plugins.

System.InvalidOperationException: An attempt was made to use the context while it is being configured

I have implemented custom ASP.NET Core middleware which uses database context as a dependency. Sometimes it throws the following exception for the very first request coming to the API:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: An attempt was made to use the
context while it is being configured. A DbContext instance cannot be
used inside OnConfiguring since it is still being configured at this
point. This can happen if a second operation is started on this
context before a previous operation completed. Any instance members
are not guaranteed to be thread safe.`
I could reproduce it only when API was called from SPA. When I called API from Swagger everything was working just fine. Changing order of middlewares didn't help. After digging around I realized that middleware was instantiated once per application while the database context had a scoped lifetime. So perhaps the issue was in injecting my database context right into middleware's constructor. I fixed my code by removing injection of database context from constructor and injecting it directly to InvokeAsync method. This helped and exception gone.
Though I solved my issue I don't quite understand yet how it worked at all. As far as I understand the EF.Core database context by default is registered with scoped lifetime what in terms of ASP.NET Core application means that new context gets instantiated for every new request and disposed upon its completion. Because I injected the database context into middleware's constructor it should have been disposed right after first request finished and this exceptions or another one saying that it's trying to use already-disposed context should have been thrown. Also it's absolutely not clear to me why this error was happening only when API got called from SPA while it was working good for all Swagger requests.
Seems I have figured it out. I didn't mention that I use Autofac service provider instead of default service provider in my application which in fact was worth to mention. According to ASP.NET Core documentation
The Default Service Provider in Development environment performs
checks to verify that:
Scoped services aren't directly or indirectly resolved from the root service provider.
Scoped services aren't directly or indirectly injected into singletons.
Apparently Autofac service provider doesn't perform such checks so it allows to inject scoped services from root service provider. And according to documentation
The root service provider's lifetime corresponds to the app/server's
lifetime when the provider starts with the app and is disposed when
the app shuts down.
This is why my application worked as expected though I injected scoped service into singleton. It used the instance of DbContext resolved from the root service provider and sometime I could get such situation when I tried to perform query to database before the context was actually initialized. This explains the sporadic nature of this issue.
I had the same issue, I resolved it as mentioned in the answers to this question.
added "ServiceLifetime.Transient" option to the db context.
at Startup.cs added:
services.AddDbContext<TableContext>(opt =>
..otherOptions.., ServiceLifetime.Transient);

HTTP Request processing in ABAP system

I have a very basic question in how a external HTTP request is processed in an ABAP (S/4 system).
Are the requests handled by per process or per thread. (terms taken more from the java http world). ?
By threads will mean which already have the objects initialised in memory by the previous request.
By process will mean that the objects are initialised in memory every time which is obviously time consuming and non performant.
In case of a clustered system the request can be load balanced to a new systems which is a separate topic.
Best Regards,
Saurav
Internet Communication Manager (ICM) handle request and forward it to your class which is extend from IF_HTTP_EXTENSION interface by url (configure it in SICF).
SAP need authorization for accept http request. Web logon screen set cookie to client for tracking it. If you configure static user to your service on t-code SICF, you can add cookies to client (with http header in response) for tracking and checking it.
There is no cache for object in this interface, but you can create your own with static class attributes and other general function caching capabilities from ABAP. Please check below rest service api for sample project:
https://github.com/pacroy/abap-rest-api
Load balancers has cookie based route capabilities (session based) for finding correct system.

Session variable equivalent in OWIN self-host

I have a sample web API hosted in an OWIN process (self hosted, not in IIS). I get a JWT token in my controller and I want to be able to retreive it in another part of the application, a class that implements NserviceBus IMutateOutgoingTransportMessages. In my other web application POC (hosted in IIS), I used a simple session variable and it works just fine. But I'd like to know what would be the best way to do it in my new OWIN self hosted environment ? Static property in static class ?
This question is really broad and difficult to answer without detailed knowledge of your specific needs. Here's my interpretation of your issue:
You're already signing each request, perhaps storing the token in the browser sessionStorage (or even localStorage), but this does not suffice
You need to retrieve the token outside of or not in relation to any request cycle (if not, this is probably where you should be looking for answers)
Your application does not need to be stateless
Just one static property for one token in a static class would of course start breaking as soon as more than one request hits the application at the same time. Implementing a class that maintains a list of tokens may be a solution, although I can't tell what key you should use to identify each token. Interface details would vary depending on things like if you need to retrieve the token more than once.
Thread safety issues would apply to all handling and implementation of such a class. Using Immutable Collections and functional programming practices as an inspiration may help.
If lingering tokens poses a problem (and they probably would from a security perspective, if nothing else), you need to figure out how to make sure that tokens do not outstay their welcome, even if the cycle is for some reason not completed.
Seeing how you used Session as a solution in your POC, I'm assuming you want some similar behavior, and that one user should not be allowed to carry two tokens at the same time. You could store the tokens i a database, or even in the local file system, making maintenance and validity a separate issue all together.
There are implementations of cache-like functionality already available for OWIN self-hosted applications, and maybe one of those would serve as a shortcut to implementing everything yourself.
If this token business in fact is the only reason for introducing state in your application, then the best solution IMHO would be to rethink your architecture so that the application can remain stateless.
I'm facing a similar dilemma on a server i'm currently developing for a customer. My problem is that the server must make calls (and retain a live connection) with a legacy, multithreaded DLL, (aka the SDK).
I struggled to get this working on IIS with a regular Web API project. Failed badly since IIS recycles threads when it determines that a thread is going rogue... witch is what the SDK thread looks like in that perspective. Also, the SDK must be able to callback on the caller (client - single page app) and for this I'm using SignalR.
I then tried a multi-part system (single page + web api on IIS + WCF service for the SDK integration). But it is a real nightmare to manage because of the 2 way async communication that must occur between all apps. Again: failure.
So I reverted to a single self hosted OWIN + WebAPI service in a console app (for now). My problem is that some of the calls are lengthy and are processed in a worker thread. I managed to pass the SignalR client id in each ajax calls via headers. I can extract the id when in web api controller. But when the task goes async, I need to get the id (via an Unity injected service) from the class that manages the async task. This is where my problem is similar to yours. In IIS hosted apps, we have HttpContext. It is contextualized on each client calls, and follows any thread changes in the pipeline... But not in self hosted OWIN WCF apps...
I'm looking into Thread Local Storage, CallContext... and other means of keeping track of the original caller info during the lifecycle of the async call. I have read about OWIN pipeline, I can capture the info in a OWIN middleware... but how to safely keep that info for use in injected services? I'm still searching for an answer...
I was wondering if you have found a solution to this rather interesting problem ?
I prefer adding to your thread rather than start another parallel thread / SO question.

Custom authentication, authorization and session for WCF

I have read about various implementations of authentication and authorization for WCF, starting from reusing some built in .NET and WCF features and ending with completely custom implementations.
But there are so many factors to take into account, so I'm confused about how to implement it for my intranet business application project.
Here is what I need:
- WCF .NET 4.5 services will be hosted in IIS 7 or newer.
Most probably, ASP.NET compatibility will be disabled.
Protocol will be HTTP with BasicHttpBinding, but it might need binary serialization to minimize traffic.
WCF method will receive a custom session ID which will be checked against a user session object in a database. No .NET sessions are allowed in this project.
After receiving the ID, the service will read the corresponding user data (including authorization flags to see if the user is allowed to execute the current operation) and validate it. If data is invalid, an exception will be thrown and the WCF operation won't be executed. If validation succeeds, the identity of the user will be stored in a current operation context (and also current thread principal) so it can be accessed by various components during the WCF operation execution.
All the authentication&authorization should be done transparently before the execution of the WCF operation - without additional efforts from programmers who will create the WCF methods.
I need access to the WCF operation name being executed, when I perform the auth validations, so I can throw an exception if the user does not have permissions to execute the operation.
testers will use SoapUI, so they'll need to be able to pass the session ID through standard SOAP or HTTP headers.
Which would be the most straightforward way to implement my auth routines? Should I use a custom binding? Custom behavior? Some kind of a built-in request event handler (which one exactly, and will they work if ASP.NET compatibility is disabled)? Authorization policy (seems a bit overkill because I won't be using most of its built-in features anyway)? Something else?
You can try making use of Message Inspectors. Your session ID can be passed like a token through SOAP or HTTP Headers and will be inspected by WCF through your defined behavior before it executes the actual service operation.
You can check the articles here and here, particularly focusing on the IDispatchMessageInspector interface which offers the "AfterReceiveRequest" and "BeforeReceiveReply" methods.