Why I'm getting always a new session in SparkJava? - session-cookies

I have a SparkJava api filter that is called by my client every 30 seconds.
before("/app/*", {
req, _ ->
println(req.session().attributes().size)
println(req.session().id())
println(req.session().isNew)
req.session().attribute("test", "test")
})
The result is:
0
node0r3ulllnarwq5i62o2wcpxmu25
true
0
node0i0morm89ftci1tntiu38p8l5026
true
0
node09n12ooeo0t34wkpaqfhbbou227
true
You can see above, the session id is always different.
Why the session is always a new session?

I was stupidly mistaken, but the behavior is correct. REST is stateless and has no session.
There is a good explanation:
If REST applications are supposed to be stateless, how do you manage sessions?

Related

Is there any way to store values in OPA

I have a usecase to do like, if a variable is already defined then return that value else invoke a rest endpoint to get the variable.
get_value = value {
data.value
value
}else = value {
value := <> #invoke rest
}
I will be running OPA as a server and my expectation is like, in the first invokation it will go to the else block then to the first block for rest of the calls. Could you please help me
You cannot write to the in-memory store from a policy, no. Except for that though, your code looks fine, and I'd say it's a pretty common pattern to first check for the existence of a value in data before fetching it via http.send. One thing to note though is that you may use caching on the http.send call, which would effectively do the same thing you're after:
value := http.send({
"url": "https://example.com",
"method": "get",
# Cached for one hour
"force_cache": true,
"force_cache_duration": 3600
})
If the server responds with caching headers, you won't even need to use force_cache but can simply say cache: true and the http.send client will cache according to what the server suggests.

How to not make the user re-login every time browser closes?

This might be a basic/dumb question, but I don't know the right keyword to Google. What I want is that when I authenticate the user to my web app, they can close the browser, and when they open it back, they can still use my website - they are not logged out (yet).
I have been following the tutorials in IdentityServer docs (https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html), and so far I have managed to get the whole IDP-API-Client working. I have inspect the token that I get from IDP, it's valid for 2 weeks, so what am I missing here, why do I get logged out when I close the browser?
My guess is that I need to store the token to the cookie, but how do I save it, and how do I force the web application to always check for the cookie?
The IS4 tutorial has this:
services.AddAuthentication(o =>
{
o.DefaultScheme = "Cookies";
o.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", o =>
{
o.Authority = "https://localhost:5001";
o.ClientId = "mymvcclient";
o.ClientSecret = "mymvcclientsecret";
o.ResponseType = "code";
o.SaveTokens = true;
o.Scope.Add("myapi");
o.Scope.Add("offline_access");
});
I assume that's just creating a cookie, but how do I specify for it to save my token, and read the token from the cookie when user opens my web application?
Yea there is an option called ExpireTimeSpan in your cookie handler, which defaults to 14 days. You can change it to anytime longer than that by just setting a value to it:
...
.AddCookie("Cookies", options => {
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.SlidingExpiration = false;
})
.AddOpenIdConnect("oidc", options => {
...
options.UseTokenLifetime = false;
...
})...
The above sets the cookie expiration to 30 days, instead of the default 2 weeks.
You also want to make sure the UseTokenLifetime option from the OIDC is set to false, which is the default for now I think. Tokens coming back from the Identity Server, for example, tend to have short lives. If you set it to true, which was default before, then it would override whatever expiration you set earlier.
The best term to look for on this is probably "persistent sessions", or just session management in general. This is something handled by ASP.NET Core, not really IdentityServer. There are several mechanisms to maintain session state on the server, which you'd need for example not to lose all sessions when a server restart happens.
I've had the best luck using the ITicketStore interface, which allows persisting the sessions to a database. The cookie ends up with a session ID which is validated on each request for expiration.

Session Authentication not working in Play when using Silhouette

I am using Silhouette security library. My Play server seem to send empty Session information in response. What am I doing wrong?
Following is the print on Play's console just before sending response.
Session(Map(authenticator -> 1-jtwBvA+LsLKE2rnkT/nMH1aQF9xc1twhECrma9mj3NUhUdVDmh/4wxQ2MxDOjcxkvEMTi1k63Dg5ezl+9FzDE3miaM5DbOrhyqAyGu4+30mHHV3QdPKA3IQQx5UdL1Hu85fZRI4f3Ef+q6xAgboDps0uBob5ojzo5Oqy8FNsoexn7Wr9iRyTr5xrMrLvl9GNQa+rA3q8qvW84sJaSei2iydrP2OjUbnnzo+zgrHLB3Bn7KJxOcFH4h9CikZNk/FHbtDm4uxzcK3paK1CuuIWLE8yvcYdavJ+4ejV5IaJ8QesJQRFgBktD9L/A2bc03eaA8wm)))
But in the the browser window, I notice that the value is empty.
Set-Cookie: PLAY_SESSION=; Max-Age=-86400;
Note that my browser earlier already had a PLAY_SESSION cookie from previous test runs. However, I would expect that the client application (Angular) would override old cookies with new cookies. Am I correct?
Following is the code snippet which creates, initialised and embed session information
val AuthenticatorFuture: Future[SessionAuthenticator] = silhouette.env.authenticatorService.create(loginInfo) //create authenticator
AuthenticatorFuture.flatMap(authenticator => { //got the authenticator
val securityTokenFuture: Future[Session] = silhouette.env.authenticatorService.init(authenticator) //init authenticator
securityTokenFuture.flatMap(securityToken=> {
println("adding security token: ",securityToken)
val result:Future[AuthenticatorResult] = silhouette.env.authenticatorService.embed(securityToken, Ok(Json.toJson(JsonResultSuccess("found user"))))
result
The Environment is defined as
trait SessionEnv extends Env {
type I = User
type A = SessionAuthenticator
}
As is passed to my controller as
silhouette: Silhouette[SessionEnv]
I created is at compile time as follows
val configSession = SessionAuthenticatorSettings()
val sessionAuthenticatorService = new SessionAuthenticatorService(configSession,fingerprintGenerator,authenticatorEncoder,new DefaultSessionCookieBaker(),clock)
val sessionEnv = com.mohiva.play.silhouette.api.Environment[SessionEnv](userIdentityService,sessionAuthenticatorService,Seq(),EventBus())
The issue is probably expected behavior of Play Framework as Silhouette doesn't modify the session cookie. I noticed that the browser already had a previous expired cookie and it sends it in the signin request. When Silhouette authenticator sees the expired cookie, it sends an empty value back. I think this is to make the browser discard the previous cookie.

when nusoap is calling a web service from PHP application, handling timeout issues

I am using nusoap in my PHP application when calling a .net webservice.
The issue is, in some cases .net web service is taking more than actual time for some request, so I want to increase the time my SOAP call waits for the response.
Is there any function or any way that I can keep nusoap call waiting until I get a response from the webservice.
Thanks,
Rama
Nusoap default timeout is 30 secs.
Increase Response timeout to solve this problem.
// creates an instance of the SOAP client object
$client = new nusoap_client($create_url, true);
// creates a proxy so that WSDL methods can be accessed directly
$proxy = $client -> getProxy();
// Set timeouts, nusoap default is 30
$client->timeout = 0;
$client->response_timeout = 100;
Note : This settings also didn't work for some time. So i directly went to nusoap.php file and changed $response_timeout = 120. By default this value set to 30 secs.
It is solved now :)
References : Time out settings - Second reference
When you create the istance of the nusoap_client try
$client = new nusoap_client($$creat_url, true,false,false,false,false,0,300);
where all the false parameters default to false,
0 is the timeout and 300 is the response_timeout
Thanks

Handle session expire in MVC 2 with ajax

I want to check the session expired or not.
SO what i decided is Create an action called IsServerExpired and have it return a json object containing a boolean value, and the redirect url.
SO the java script function will do an ajax request to this action with specified time interval ..
I have some basic questions ..
1.If i send an ajax request ,i think that will refresh the session time . So in effect the session will not expire if i am using this method. am i right ?
If it refreshes how can i check session expire using polling
There is more simple approach to log out user once session expired.
You can save SessionTimeout somewhere on the client side and run client side timer, once timer reach end redirect user to log out url.
Here is example. Model here containts SessionTimeout value.
$(document).ready(function () {
var timeOutInMinutes = #Model;
if(timeOutInMinutes > 0)
{
setTimeout(function() {
window.location =
'#Url.Action("Logout", "Authentication", new {area=""})';
},timeOutInMinutes * 1000 * 60);
}
});
More user friendly way is to show popup that will say that session will be expired wihtin one minute(if session timeout 15 mins then show it after 14 mins), so user will be able refresh page. and continue work.
I think you are confusing between an ASP.NET session and the authentication cookie. I suspect that you are talking about the authentication cookie expiration here. If you have set slidingExpiration to true in your web.config then polling AJAX requests will renew the timeout so they are not suitable. Phil Haack described a very elegant way to detect authentication cookie expiration in AJAX calls in this blog post.

Resources