cPanel, Laravel TokenMismatchException with Cookies not being set - authentication

I recently moved my laravel application to a production server rather than just developing locally. However since doing so I have been unable to login to the site as I keep running into Illuminate \ Session \ TokenMismatchException.
I never had the issue on the local server, just when I ported it over the production server.
I have looked into the tokens and they never match at all. My code is as follows:
Route::filter('csrf', function()
{
// Check ajax requests for token validity via the header.
// app.js has the code to grab form tokens and put it in
// a header, well validate it here if its a post AJAX
if (Request::ajax() && Request::getMethod() == 'POST')
{
if (Session::getToken() != Request::header('X-CSRF-Token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
} else {
if (Request::getMethod() == 'POST' && Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
}
});
The error occurs when I am trying to compare Session::token() to Input::get('_token)
So my question is, is there something blatantly obvious that I am missing in regards to the difference between tokens on a local server to that of a production server?
Any help on this would be greatly appreciated!
~Additional Information~
From the other sources I've found there are similar issues where the session isn't persisting. I'm already on Laravel 4.1 so the lifetime and expire_on_close are already set to the default of 120 and false. I have also tried changing the session driver to file/database/cookie all with the same outcome.
~Another Update~
Ok, somewhere a bit closer, looking into browser resources, on my local server a cookie is set laravel_session, however on my web server this is not appearing at all. So think this is related it.

I couldn't solve this. In the end though I found that is was related to the use of cPanel, as soon as I used another hosting provider without cPanel the issue has never occured.

Related

ASP.NET Identity Core: invalid token for password reset on web farm

So, I've been reading the docs and I'm trying to make my site on a web farm. I've searched a lot of articles and it seems like setting the keyring to a common network path should be all that is required to get the data protection to work. In my case, I'm persisting it to Azure.
Now, authentication is working fine, but I'm always getting the Invalid Token error when a user tries to reset his password (when the link is generated on one machine and verified on another).
EDIT: added code for generating the link and verifying the token.
Btw, here's the code used for generating the reset link with the token:
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
await _emailSender.SendPasswordResetAsync(user,
User.IsAuthenticated(),
Url.Link("default",
new {
Controller = "Account",
Action = "ResetPasswordEmail",
token = code,
email = user.Email
}),
_dbContext.Database.GetDbConnection(),
CancellationToken.None);
And here's how it's validated:
var validToken = await _userManager.VerifyUserTokenAsync(user,
"Default",
"ResetPassword",
token);
Any ideas on what's going on?
Thanks.
Ok, as always, the problem was between the chair and the keyboard...
The problem was that the keyring was setup to use azure inside an #if RELEASE condition which wasn't set up on the publish pipeline...
Bottom line: sharing the keyring is all that was needed to get everything up and running...

Expressjs cookie-session settings not working with Passportjs

I'm trying to call my /auth/user endpoint to get the current user that's logged into my website. But because of the new Chrome update I need to somehow set 'sameSite' and 'secure'. Anyone know of how I can get around this? Am I doing something wrong with cookie-session?
The cookie gets sent by express just fine, but it doesn't come with sameSite and secure settings that I specify in the cookie-session settings (see image). I tried with express-session as well, but for some reason the sameSite and secure settings never propogate to cookie used for oauth.
Btw, the authentication works on localhost addresses, but when I deploy from frontend and backend with heroku, I encounter the issue where I need to set sameSite. Would setting up a proxy or something get around the sameSite issue?
I am working on the same issue. SameSite=None needs the cookie to be secure
https://www.chromestatus.com/feature/5633521622188032
Eventhough I have set "secure: true" I am still seeing the cookie not being created on Chrome, but I do see it on Edge
After 3 days trying to figure It out. I finally found a way around this issue, It's not a fix, I'm quite sure PassportJS will come with a solution for that eventually, but for now It allowed me to get the user from the authentication.
Since we are not being able to get the user from the cookie, but the information is in the server session, the way to get this information is to add to the 'server.js' a route to get the user directly from the server session:
app.get('/api/getUser', (req, res) => {
res.json(req.session.user);
});
For some reason, I suppose the lack of cookie somehow, using the req.session inside of a router is returning undefined, but If used inside 'server.js' (or your server index file) It gets the session.
If you need the req.user._id or some other sensitive information for other requests, I would recommend returning a jwtToken with this information to the frontend (in res.json), then save the token directly in localStorage and pass the token in the body of your requests, is not the ideal, but It's the safer way I could think to keep the ids safe.
I hope It can help you!

identity server multiple issues after deployment

My current setup is like this. The entire project was built using the official docs here - https://identityserver4.readthedocs.io/en/latest/
API Server
Auth Server with local login, google login and github login
Console based c# client
JS based client
MVC based client.
(all of it, as described in the official docs)
Locally, all of them work beautifully. Able to login, access api endpoints, logout, redirect, the whole thing works smooth.
I have deployed all 5 of them to five different azure web apps. They all have the standard xyz.azurewebsites.net domains ready to use. Now, I have run into some problems.
the console C# client is able to talk to the deployed auth server, collect token using a local account on the auth server and make calls to the deployed API server. Based on this, I assume that both the api server and the auth server working hand in hand, as they should.
Problem #1 - the JS client keeps saying
'The login is blocked because of CORS Missing Allow Origin '
Problem #2 - the MVC client loads the auth server, and then the auth server gives me this error.
Sorry, there was an error : unauthorized_client
Request Id: 80005c0f-0000-eb00-b63f-84710c7967bb
Note : I have set the CORS policy on the auth server, both these clients, under client definition as follows. I am not too concerned about keeping the auth server open, so dont mind if any and every domain can call the auth server.
AllowedCorsOrigins = { "*.*" },
Also Note : I have set the URLS in the code before deployment. all loclahost:port number lines have been replaced correctly with the corresponding now published URLs.
So, what am I missing out here?
Update 1
I was able to solve the CORS issue. Have posted a answer here on another question.
Not able to enable CORS for identity server 4 in asp.net core
Update 2
So, now, both the JS client and the MVC client, are giving identical errors.
Sorry, there was an error : unauthorized_client
Request Id: 80005c0f-0000-eb00-b63f-84710c7967bb
Update 3
I have opened an issue which has log details.
https://github.com/IdentityServer/IdentityServer4/issues/4691
I am not sure if this counts as an answer, but posting for my own question, as it might might help others. Also, this is only a guess at this point.
I found out that the redirects were permanently stored in the database I used with EF migrations. That mean, local in memory redirects were being overwritten anyway by the database stored migrations. I believe this is the issue.
I also realized that the console app is working fine for it does not depend on redirect URLs where as the JS and MVC based clients dont work because they do depend on redirect URLs.
At this point, the best thing to do and for you (if you used EF migrations to store your auth server configuration) on database would be start over and switch to in memory only. Alternatively, you can try and update the database to suit your deployment requirements.
Ultimately, I believe, unless it is absolutely necessary, keep the auth server config (like redirects and CORS settings) in memory as they dont take up much value and are rarely changed.

"hostname doesn't match" when using requests in PythonAnywhere

EDIT: I fixed the problem, see links in the answer.
I'm using the XMLHttpRequest AJAX API to send data from different websites to our server in PythonAnywhere.
Something odd happens: depending on the website, either we send successfully or we get this error
POST https://canecto.pythonanywhere.com/api/ 500 (Internal Server Error)
even though the same code is loaded.
I tried to manually open the request and send data via JavaScript console in Chrome but nothing changes.
Here is how the snippet looks like:
var url = "https://canecto.pythonanywhere.com/api/";
var xmlHttpPost = new XMLHttpRequest();
xmlHttpPost.open("POST", url, true);
xmlHttpPost.setRequestHeader("Content-type", "application/json");
var postData = {
page_url: window.location.href,
time_on_page: activeTime,
cookie: cookie,
/* some variables */
};
xmlHttpPost.onreadystatechange = function() {
if (xmlHttpPost.readyState == 4 && XMLHttpRequest.DONE) {
console.log('');
}
};
/* send data */
xmlHttpPost.send(JSON.stringify(postData));
I read here that the problem should not be the client-side JavaScript.
If I inspect on the server side, for the line requests.get(page_url, headers=HEADER, timeout=10)(where I try to access the page) I get this log:
I read on the Python request library that it may be something related to the SSL verification, but I have very little clue about it. I tried to check other similar questions but I have not found the answer.
Has anybody experienced anything similar and successfully solved it?
To whom it still uses Python < 2.7.9: this answer worked for me. SNI is not supported in Python 2, that means you should follow such answer and these requirements to make requests work with SSL certificate verification.

Laravel 4.2 User Authentication Across Subdomains on Server

Authentication persists nicely across my subdomains on my localhost thanks to help I received here. But now I'm having trouble my remote server. I changed 'domain' => '.mydomain.com', in session.php and now I can't log in at all. Actually, Auth:attempt() works just fine but it fails my auth filter when it then attempts to load the next page. Here's the code in my filter:
if ( Auth::guest() ) return Redirect::guest('login');
To me this means that sessions aren't working at all. And that line that I changed in session.php is definitely the culprit, because when I change it back to 'domain' => null, I can log in just fine... it just doesn't persist across subdomains. Any ideas on getting laravel to remember sessions across my subdomains?
Do all of this login testing in private windows, as old persisting cookies can really screw you up.