Session Cookie never set in asp.net core - session

I am trying to configure sessions for an asp.net core 2.0 website, but the session cookie is never set.
I call ..
app.UseSession();
...in Startup.Configure and ...
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = false;
options.Cookie.Name = "WS_AUTH_ID";
});
... in the ConfigureServices method.
In the Controller I can acess ...
HttpContext.Session.Id;
... but the id is always different for every request.
Am I missing something?
Update: I should metion that I can set cookies "manually" and the browser will "receive" them.
HttpContext.Response.Cookies.Append("Test_cookie", "yo");

This was the cause for me:
The extension Microsoft.AspNetCore.CookiePolicy (UseCookiePolicy) was blocking the session cookie. Removing this extension and running the app in a new browser window fixed the issue.
Rationale: this extension blocks the cookies sent to the browser until the user accepts them. Since the session key is stored in a cookie and cookies are blocked by this extension... No cookies, no session.
Another workaround could be to enable the application to work without session until the user accepts cookies (I didn't test this workaround).
Hope that helps.

If you have the cookie policy turned ON the session cookiewon't be created until the user accepts the use of Cookies, this is to comply with the EU's GDPR.
You can remove the line
app.UseCookiePolicy();
from you Startup and then it will work, otherwise your users will need to agree to the use of cookies before you can use the cookie for session control.

For me the problem was solved by one of the comments on the question:
The cookie isn't written unless you add something to the session.
So just requesting the Session.Id won't help, you actually have to set something.
In my case it was a variable that was only set after some condition, and before that condition was met, it would create a new session ID over and over again.

You have to type the following in your ConfigureServices method:
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.Name = ".MyApplication";
});
In your Configure type the following
//enable session before MVC
app.UseSession();
app.UseMvc();

Related

Yii2 $session->setId() not working

I'm using Ajax to log in a user from subdomain. The Yii2 app is on another subdomain. Both subdomains are configured to use same cookie and session domains and save paths. I'm including session ID with Ajax call to write the user information to the same session used by non-app subdomain like this:
$session = Yii::$app->session;
$session->open();
$session->setId($post["session"]);
$session["user.id"] = $user->id;
echo $session->id; // This does not return the same ID originating from post!
Unfortunately the user information IS NOT written to the session already existing, but a new one. Is there a session involved somewhere in the middle of login process or why isn't it working? I've also tried session_id($post["session"]), but nothing.
This was actually working on previous domain, so I must be missing something. All of the AJAX posted info is correct and checked, the user is logged in properly (checked the logs) but into wrong session.
Thanks in advance!
yii\web\Session::setId() is a wrapper for session_id(), you should read PHP documentation about this function :
string session_id([ string $id ])
If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose.
So you should simply try :
$session = Yii::$app->session;
$session->setId($customId);
$session->open();
I Don't think you are following the correct way to SET & GET session.
Try This:
$session = Yii::$app->session;
$session->open();
$session->set('id', $post["session"]);
echo $session->get('id');
For more info, please click Session Management - Yii2

How to disable sessions, cookies and auto login in Yii2?

I am building stateless restfull API in Yii2. So I created new APP in my advanced app layout (as preferred by Yii2 creators) and configure all necessary things and API worked.
Now I want to make it stateless - I want to disable session and I want it to be accomplished in config/main.php inside my API app to ensure it as global setting.
Also I want to disable cookies and auto login.
What I have been playing now so far is inside Module class
<?php
namespace api\modules\v1;
use \app\models\User;
use yii\filters\auth\HttpBasicAuth;
class Module extends \yii\base\Module
{
...
public function init()
{
parent::init();
\Yii::$app->user->enableSession = false;
\Yii::$app->user->enableAutoLogin = false;
}
...
}
But when trying to access data using POSTMAN on Chrome I can see that:
Cookies are set (PHPSESSID, _csrf, _identity)
I always get popup asking for username and password
Thanks for your help in advance!
Finally I found out what the problem is. Yii2 worked OK, but Postman had some data stored from the past when cookies and session were enabled. What helped me was deleting browser's history (including cookies), close all instances of browser and rerun.

cakephp, session not working unless allow a cookie in browser

Using latest version of cakephp v2.3.3
I have a problem with my session variables when a browser doesn't allow cookies.
I pass variables from one controller to the other and this works perfect as long as the browser has cookies enabled. I have tried it with the Session helper in the controllers, but no effort, same problem.
How to fix this, is there a work around???
Cookies are required to keep track of the session ID, but you can manually get or set the session ID using $this->Session->id(). By adding the code below to the App Controllers' before filter you can set the session ID as a URL paramter like http://example.com/posts/view/1?session=qkv108c2pqeubcpeos1q7ekds3, for example.
if (!empty($this->request->query['session'])) {
$this->Session->id($this->request->query['session']);
}
The session ID is required for every request which means you have to include it in every link. I would suggest extending the HTML helpers' url and link methods to automatically add it.
Edit:
You should verify that $this->Session->read('Config.userAgent'); or $this->request->clientIp(); has not changed since the user was authenticated to prevent session hijacking. Thanks to thaJeztah for pointing this out.

How to clear cookies of HttpWebRequest in WP7?

My logout does not seem to work.
I clear cookies like that:
foreach (Cookie cookie in _session.Cookie.GetCookies(new Uri(Session.ServerSecureURL + "/Login", UriKind.Absolute)))
{
cookie.Discard = true;
cookie.Expired = true;
}
But next time I try to login, I get the previous user's session, even though, I verified, and in the web request I see a new cookie.
Anyone had similar problems with cookies?
I Found the problem. It was not Cookie related after all.
I used wireshark to see what is sent to the server, and found out that after i logout there is only one call to the server, the one that logs me back in, but no calls to retrieve the data are made. Apparently WP7 retrieves me the old data from previous session from cache. I fixed that by adding a random data to the end of my url, and now it works perfectly. I'm still wondering what is the right way to control caching on WP7.
This:-
new Uri(Session.ServerSecureURL + "/Login", UriKind.Absolute)))
Looks a little suspect to me. I would expect it to be:-
new Uri(Session.ServerSecureURL + "/", UriKind.Absolute)))
Ordinarily cookes set in a folder (like "Login") would still have the path "/", since its usually intended that the cookies be available to the whole application.

Magento frontend (session) cookie

i have some strange behaviour in IE on my magento shop with loosing the frontend (session) cookie. does anybody has a clue, where in the magento code the frontend cookie gets set?
Thanks!
Afaik, the 'frontend' cookie gets set right before the current action is being dispatched.
Have a look at Mage_Core_Controller_Varien_Action::preDispatch().
Session start
Looking into preDispatch(), find the line which starts the session:
Mage::getSingleton('core/session', array('name' => $namespace))->start();
Which usually (if not overridden) finally maps to
Mage_Core_Model_Session_Abstract_Varien::start()
This is the place where all the standard session stuff gets initialized, including cookie settings by using session_set_cookie_params.
Revalidation
Be aware though, that once the cookie already exists, first cookie mangling may already happen while the core session gets instantiated, i.e. before start() is called. That's because the constructor calls revalidateCookie() while instantiating the core session. See:
Mage_Core_Model_Session_Abstract_Varien::init()

Resources