PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cookies. Show all posts
Showing posts with label cookies. Show all posts

Tuesday, November 15, 2022

[FIXED] how can i fix undefined varriable in laravel?

 November 15, 2022     cookies, css, laravel, laravel-6, session     No comments   

Issue

i wrote a code in my blade page in LARAVEL that can change them dynamically by user .

i save css styles in cookie and i defined css variable in my codes

but in main page i get this error : Undefined index: css

my code :

 <?php
session_start();

$default = 'dark.css'; // define stylesheets
$darkcss = 'dark.css';
$lightcss = 'light.css';

$expire = time()+60*60*24*30; // how long to remember css choice (60*60*24*30 = 30 days)

if ( (isset($_GET['css'])) && ($_GET['css'] == $lightcss) ) { // set cookie for light css
    $_SESSION['css'] = $_GET['css'];
    setcookie('css', $_GET['css'], $expire);
}

if ( (isset($_GET['css'])) && ($_GET['css'] == $darkcss) ) { // set cookie for dark css
    $_SESSION['css'] = $_GET['css'];
    setcookie('css', $_GET['css'], $expire);
}

if ( (isset($_GET['css'])) && ($_GET['css'] == $default) ) { // set cookie for default css
    $_SESSION['css'] = $_GET['css'];
    setcookie('css', $_GET['css'], $expire);
}

if (isset($_COOKIE['css'])) { // check for css stored in cookie
    $savedcss = $_COOKIE['css'];
} else {
    $savedcss = $default;
}

if ($_SESSION['css']) { // use session css else use cookie css
    $css = $_SESSION['css'];
} else {
    $css = $savedcss;
}

// the filename of the stylesheet is now stored in $css
echo '<link href="/admin/assets/css/'.$css.'" rel="stylesheet" type="text/css" />'
?>

Solution

problem is here

if ($_SESSION['css']) { // use session css else use cookie css

in this line u miss isset() that's why u r getting error



Answered By - Kamlesh Paul
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 14, 2022

[FIXED] How can I use Flask WTForms and CSRF without session cookie?

 November 14, 2022     cookies, flask, flask-wtforms, python, session-cookies     No comments   

Issue

I have a very simple app that has no user management or any Flask-Login auth needs. It has forms, WTForms. All I want to do is collect some data submitted by the form. I could technically disable CSRF validation but Flask WTForms really urges me not to.

I'd like to disable flask session cookie in the browser because it seems unnecessary and I would need to put a cookie banner for GDPR compliance. So to avoid all that, I thought of disabling flask session cookie as follows:

class CustomSessionInterface(SecureCookieSessionInterface):
    """ Disable session cookies """
    def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:
        return False

# App initialization
app = Flask(__name__)
app.session_interface = CustomSessionInterface()

But doing so leads to a 500 error: "The CSRF session token is missing". However, looking at the HTML that was rendered has the following csrf token rendered properly:

<input id="csrf_token" name="csrf_token" type="hidden" value="ImI2ZDIwMDUxMDNmOGM3ZDFlMTI4ZTIzODE4ODBmNDUwNWU3ZmMzM2Ui.YhA2kQ.UnIHwlR1qLL61N9_30lDKngxLlM">

Questions:

  1. What is the relationship between CSRF token validation and session cookie? Why is a cookie necessary to validated the CSRF token?
  2. I tried enabling session cookies again, deleting the cookie in Chrome developer tools leads to the same error. So, indeed, session cookie seems to be absolutely necessary to validate CSRF token.
  3. How can I use CSRF form validation without a session cookie?

Thank you so much.


Solution

I found out from the code base of WTForms: https://github.com/wtforms/flask-wtf/blob/565a63d9b33bf6eb141839f03f0032c03894d866/src/flask_wtf/csrf.py#L56

Basically, session['csrf_token'] is stored in the session and compared against the form.hidden() tag (or form.csrf_token) in the HTML body.

This is not clearly explained in the docs. But the codebase makes it clear. I guess there is no way to do CSRF protection without secure cookies.

The downside of this is that you can't get rid of cookies. I suspect, one could build a server-side session database, but then there are issues with scaling your Flask app horizontally.



Answered By - Neil
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to disable cookie handling with the Python requests library?

 November 14, 2022     cookies, python, python-requests     No comments   

Issue

When I use requests to access an URL cookies are automatically sent back to the server (in the following example the requested URL set some cookie values and then redirect to another URL that display the stored cookie)

>>> import requests
>>> response = requests.get("http://httpbin.org/cookies/set?k1=v1&k2=v2")
>>> response.content
'{\n  "cookies": {\n    "k2": "v2",\n    "k1": "v1"\n  }\n}'

Is it possible to temporary disable cookie handling in the same way you set Chrome or Firefox to not accept cookies?

For example if I access the aforementioned URL with Chrome with cookie handling disabled I get what I expected:

{
  "cookies": {}
}

Solution

You can do this by defining a cookie policy to reject all cookies:

from http import cookiejar  # Python 2: import cookielib as cookiejar
class BlockAll(cookiejar.CookiePolicy):
    return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
    netscape = True
    rfc2965 = hide_cookie2 = False

(Note that http.cookiejar's API requires you to define a bunch of attributes and methods, as shown.)

Then, set the cookie policy on your Requests session:

import requests
s = requests.Session()
s.cookies.set_policy(BlockAll())

It will now not store or send cookies:

s.get("https://httpbin.org/cookies/set?foo=bar")
assert not s.cookies

As an aside, if you look at the code, the convenience methods in the requests package (as opposed to those on a requests.Session object) construct a new Session each time. Therefore, cookies aren't persisted between separate calls to requests.get. However, if the first page sets cookies and then issues an HTTP redirect, the target page will see the cookies. (This is what happens with the HTTPBin /cookies/set call, which redirects to /cookies.)

So depending on what behavior you want for redirects, you might not need to do anything special. Compare:

>>> print(requests.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {'foo': 'bar'}}
>>> print(requests.get("https://httpbin.org/cookies").json())
{'cookies': {}}

>>> s = requests.Session()
>>> print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {'foo': 'bar'}}
>>> print(s.get("https://httpbin.org/cookies").json())
{'cookies': {'foo': 'bar'}}

>>> s = requests.Session()
>>> s.cookies.set_policy(BlockAll())
>>> print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {}}
>>> print(requests.get("https://httpbin.org/cookies").json())
{'cookies': {}}


Answered By - Mechanical snail
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I set cookie in node js using express framework?

 November 14, 2022     cookies, express, node.js     No comments   

Issue

In my application, I need to set a cookie using the express framework. I have tried the following code but it's not setting the cookie.

var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);

Solution

The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.

If express.static is handling the request, you need to move your middleware up:

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } else {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); // <-- important!
});

// let static middleware do its job
app.use(express.static(__dirname + '/public'));

Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next() when the cookie has been set.

Update

As of now the cookie parser is a seperate npm package, so instead of using

app.use(express.cookieParser());

you need to install it separately using npm i cookie-parser and then use it as:

const cookieParser = require('cookie-parser');
app.use(cookieParser());


Answered By - robertklep
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to specify the domain of cookie with Scala and Play

 November 14, 2022     cookies, playframework, scala, session-cookies, subdomain     No comments   

Issue

I want cookies which is set from test.domain.com to be set for .domain.com so that that it can still be used from anothertest.domain.com. Basically cookies should be shared between subdomains.

I called backend deployed at test.domain.com and set cookies with OK response as follows:


Ok("some response").withCookies(Cookie("id", id), Cookie("token", token))

And in application.conf I have set the session domain to ".domain.com"-


session {
\#Sets the cookie to be sent only over HTTPS.
\#secure = true

\#Sets the cookie to be accessed only by the server.
\#httpOnly = true

\#Sets the max-age field of the cookie to 5 minutes.
\#NOTE: this only sets when the browser will discard the cookie. Play will consider any
\#cookie value with a valid signature to be a valid session forever. To implement a server side session timeout,
\#you need to put a timestamp in the session and check it at regular intervals to possibly expire it.
\#maxAge = 300

\#Sets the domain on the session cookie.
domain = ".domain.com"
}

However, the cookie is being set for test.domain.com rather than .domain.com. I want to use this cookie with anothertest.domain.com .
Can you please help me with this.


Solution

You don't have to change the configuration, you can add all attributes of a cookie when creating it.

Cookie("bla", bla).withDomain(xxx)
// Or
Cookie("bla", bla, domain = XXX)

(Not sure of exact name, I don't have documentation with me right now)



Answered By - Gaël J
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the point of X-CSRF-TOKEN or X-XSRF-TOKEN, why not just use a strict same site cookie?

 November 14, 2022     cookies, csrf, csrf-token, laravel, security     No comments   

Issue

Frameworks such as laravel and others require you place the csrf token in your HTML forms.

However at the same time laravel comes by default with the VerifyCsrfToken middleware that automatically creates a X-XSRF-TOKEN cookie with the csrf token on every response. This cookie is used for ajax requests and is automatically added to the header for axios for example.

I am wondering why is it required to add the csrf token to every HTML form. Why could you not just use the already existing X-XSRF-TOKEN cookie to validate the csrf token. I understand there is the issue of same site cookies, and if your csrf cookie is set to lax or none the cookie would be sent from an external site if they would POST to my site. However this issue can be solved by setting the same site to strict then there would be no need to set the csrf token on every form which is kind of annoying to do and remember.

Is there some security concern I am missing on why we just cant use a strict cookie for validating the csrf token?


Solution

An X-CSRF-Token protects users against unwanted execution of modifying requests, which are of interest for their side effects (the changes which they make to the server, or the database), not for their response, which the attacker cannot read anyway, by virtue of the CORS protocol.

A same site cookie would protect even against execution of navigation requests, which do not change anything on the server, but only read data (including X-CSRF-Tokens for subsequent modifying requests), which is then displayed in an HTML page. For example, if stackoverflow.com had same site session cookies, you would not be able to navigate from your webmail site via a mailed link to this StackOverflow question and immediately click to upvote it, because the session cookie would not be included in the navigation request, therefore you would not be logged on at first.



Answered By - Heiko Theißen
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I use cookies with Foreach

 November 14, 2022     cookies, foreach, php     No comments   

Issue

I adopted code given in this code: https://www.w3schools.com/php/php_cookies.asp and How do I use cookies to store users' recent site history(PHP)?

and i changed the code with the link above

Example: user clicks on url

file.php?id=200&value=woman
file.php?id=150&value=woman
file.php?id=250&value=girl 

and this code is here:

$id = $_GET['id'];
$value = $_GET['value'];
$cookie_id = $id;
$cookie_value = $value ;
setcookie($cookie_id, $cookie_value, time() + (86400 * 30), "/");
if(isset($_COOKIE[$cookie_id])) {
    foreach ($_COOKIE[$cookie_id] as $cookie_id => $value) { 
        echo 'id: '.$cookie_id.' '; echo ', value: '.$cookie_id.' <br>'; 
    }
} else {
    echo 'Cookie named '.$cookie_id.' is not set!';
}

Out: the output of the code above should be as follows

id: 200, value: woman
id: 150, value: woman
id: 250, value: girl

Error: this error shows me this way.

Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/cookie.php on line 7

and also I found this code Foreach loop with cookies , but failed:

What could be the reason and what am I doing wrong?


Solution

Remove [$cookie_id] from $_COOKIE[$cookie_id]. Don't name index in foreach loop as prev variable name - $cookie_id. Name it as $ind=>$val. For debugging make print_r($_COOKIE); before loop and you'll see with what you can work further.



Answered By - mohsen
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 13, 2022

[FIXED] How do I call a non-static method from inside a static method?

 November 13, 2022     cookies, memcached, non-static, spring-mvc, static     No comments   

Issue

I have a utility Cookie class. Which has a getCookie() , trying to call a writetoCache() inside a service implementation class. But inside getCookie(), the writetoCache() is not being recognized.

This is the getCookie().

public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String mse){
//String value = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookie.getName().equals(name)){
            System.out.println(cookie.getValue());
            System.out.println(cookie.getName());
            System.out.println(cookie.getMaxAge());
            writeToCache(cookie.getName(),cookie.getValue(), 300 );
            return cookie.getValue();
        }
    }
}
return null;
 }

This is the writetoCache() inside memcached service class. I am using memcached - import net.spy.memcached.MemcachedClient;

@Override
public void writeToCache(String key, String value, int expiry) {    
    c.set(key, expiry, value);  
}

One-way is to create the instance of the non-static method's class in static method's class. But it does not work as there is type mismatch.


Solution

If your getCookie is inside the Cookie util, than you're not calling the writeToCache on memcache client instance rather as s method of Cookie. So something's not right there, double check it.

In any case, don't create a new instance, make your memcache client a singleton:

private static MemCachedClient mcc = new MemCachedClient("foo");

than call the method against the instance:

mcc.writeToCache(cookie.getName(),cookie.getValue(), 300 );


Answered By - Master Slave
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 1, 2022

[FIXED] Why is the CakeDC users plugin creating an initial cookie response when I explicitly set different settings?

 November 01, 2022     cakedc, cakephp, cookies, session     No comments   

Issue

I am familiar with the cakePHP cookie and session settings but I am unsure as to why (when analyzing through the Burp Proxy Suite I am finding 2 seperate Set-Cookie responses:

Set-Cookie: DropZone=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/
Set-Cookie: DropZone=spackr9fhhgod0lqk9glh3ch44; expires=Tue, 28-Jan-2014 23:01:37 GMT;path=/; secure; HttpOnly

I have taken the time to set HTTPOnly and the Secure flags. What I dont understand is the first line here:

Set-Cookie: DropZone=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/

Where could this Set-Cookie Header be coming from? More importantly, could this be more than an informational security threat?

I am clearly in my app/Config/core.php file setting the Session Settings:

Configure::write('Session', array(
    'defaults' => 'php',
    'cookie' => 'DropZone',
    'timeout' => 15,
    'ini' => array(
        'session.cookie_secure' => true,
        'session.cookie_httponly' => true)
));

Solution

I've tried to reproduce your issue and I see two cookies, DropZone which is in fact the default cookie name you've configured plus the other cookie Users[rememberMe] which is used by the plugin.

http://book.cakephp.org/2.0/en/development/sessions.html#built-in-session-handlers-configuration

Mine is correctly set. Also let me explain what your Cookie string means:

Set-Cookie: DropZone=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/

This says that your cookie named DropZone has been deleted. The next line creates it with the given settings:

Set-Cookie: DropZone=spackr9fhhgod0lqk9glh3ch44; expires=Tue, 28-Jan-2014 23:01:37 GMT;path=/; secure; HttpOnly

The behaviour here is correct I think, it deletes the cookie and renews it.

This cookie is definitely not coming from the users plugin as long as you haven't changed the name in the components setting to DropZone as well. So you should see two cookies.


Here is the related Github Issue: https://github.com/CakeDC/users/issues/154



Answered By - floriank
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 25, 2022

[FIXED] How to get js-cookies?

 October 25, 2022     cookies, font-awesome, js-cookie, reactjs, redux     No comments   

Issue

I used redux and I want to fetch my API using the cookies item like this:

import cookies from "js-cookies";

api/get_liste/${cookies.getItem("moncentre")}

when I run my app, ${cookies.getItem("moncentre")} is null.

My codesandbox: https://codesandbox.io/s/ecstatic-rubin-tf56r?file=/src/App.js:157-212

How can I fix it ?


Solution

So the problem here is, you never set a cookie in your app and then try to get the cookie that never exists so it will return null since there is no value for it in the browser cookies.

In order to set a cookie, you should do this (according to the package provider):

cookies.setItem('_code_sandbox_key', 'Cookie did set.')

The other thing that you facing is the warning that you get in your dev tools, so according to this doc, this console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption. To fix this you should add SameSite="none Secure" (and then clear all your cookies with the dev tool) to let the browser know the script is not related to your site and that it is a third-party library that you are using.

<script src="https://kit.fontawesome.com/a076d05399.js" SameSite="none Secure"></script>

NOTE: You can follow this thread for more information.



Answered By - SMAKSS
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to make the third party cookies in capacitor project to work for ios

 October 25, 2022     capacitor, cookies, ios     No comments   

Issue

I m working on a capacitor project that uses wkwebview, facing issue in writing cookies with ios, android works fine. Adding this to config file didn't work,

"server": {
    "hostname": "subdomain.example.com"
  }

Please advise me if i m missing out something.


Solution

As of iOS 14, you cannot use 3rd party cookies by default. Add the following lines to your Info.plist file to get better support for cookies on iOS. You can add up to 10 domains.

WKAppBoundDomainswww.mydomain.comapi.mydomain.comwww.myothercooldomain.com

source: https://capacitorjs.com/docs/apis/cookies



Answered By - Merlin B
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to implement Cypress v10 session() to persist cookies that are not initially available

 October 25, 2022     cookies, cypress, cypress-session, reactjs     No comments   

Issue

I am running cypress v10 on a react front-end and trying to get my cookies to persist through some of my tests.

I am testing the flow of logging in and out of my app. As of V10 cy.session() appears to be the way to go. However, most of the examples I have seen have just been adding a cookie in a named session object right at the start in a beforeEach().

I don't have the cookies initially available at the beginning of the test module, I create them a few tests down (as below), doing some more tests whilst logged in with the cookies and then logging out, removing the cookies.

So I'm a bit confused on how to implement session() into the mix of the following code. Could use some direction on the structure, thanks!

describe('Auth (e2e)', () => {
    
  it('should load and redirect to /login', () => {
    cy.visit('https://localhost:3000/');
    cy.wait(500);
    cy.url().should('include', 'login');
  });
    
  it('login button should be disabled initially', () => {
    cy.get('#btn-login').should('have.attr', 'disabled');
  });
    
  it('login button should be enabled upon enter valid details', () => {
    cy.get('#tbxUsername').click().type('hfisher');
    cy.get('#tbxPassword').click().type('#VS1DEV');
    cy.get('#btn-login').should('not.have.attr', 'disabled');
  });
    
  it('should navigate to the home/dashboard upon logging in', () => {
    cy.get('#btn-login').click();
    cy.wait(500);
    cy.url().should('not.include', 'login');
    cy.url().should('include', '/');
    /***** Here it finds the 4 cookies just fine ******/
    cy.getCookies().should('have.length', 4);
  });
    
  it('should have 4 cookies available', () => {
    /***** Cookies are gone at this point ******/
    cy.getCookies().should('have.length', 4);
  });
    
  it('should have a JwtToken cookie', () => {
    cy.getCookie('JwtToken').should('exist');
  });
  it('should have a SystemData cookie', () => {
    cy.getCookie('SystemData').should('exist');
  });
  it('should logout via the profile menu and navigate to the login', () => {
    cy.get('#profile-menu-icon').click();
    cy.get('#profile-menu-item-logout').click(); //Logout called here
    cy.wait(500);
    cy.url().should('include', 'login');
  });
  it('should not have any cookies after logout', () => {
    cy.getCookies().should('have.length', 0);
  });
  it('login button should be disabled after logout', () => {
    cy.get('#btn-login').should('have.attr', 'disabled');
  });
  it('should not display profile menu in the header after logout', () => {
    cy.get('#profile-menu-icon').should('not.exist');
  });
  //Login again via auto-authenticate
  it('should navigate to the dashboard from the auto-login upon clicking auto-authenticate button in the login screen', () => {
    cy.get('#autologin-link').click();
  });
});

Solution

The cy.session() command seems to only work well where the tests are decoupled, that is one does not depend on the other.

But for your test suite it doesn't seem right to move the code from the first three tests into a beforeEach() in order to use cy.session() to persist the cookies.

Instead, you can take a simpler approach - in the test where the cookies are set, save them to the environment, then add a beforeEach() to restore them.

describe('Auth (e2e)', () => {
    
  beforeEach(() => {
    const cookies = Cypress.env('cookies')   
    cookies.forEach(c => cy.setCookie(c.name, c.value))
  })

  it('should load and redirect to /login', () => {...})        // no cookies here 
  it('login button should be disabled initially', () => {...}) // still no cookies
  it('login button should be enabled...', () => {...})         // still no cookies 
    
  it('should navigate to the home/dashboard upon logging in', () => {
    cy.get('#btn-login').click();
    ...
    // Save cookies to environment
    cy.getCookies().then(cookies => Cypress.env('cookies', cookies))
  });
    
  it('should have 4 cookies available', () => {...}) // cookies are persisted here
  it('should have a JwtToken cookie', () => {...})   // cookies are persisted here

  it('should logout via the profile menu and navigate to the login', () => {
    cy.get('#profile-menu-item-logout').click(); //Logout called here
    ...
    Cypress.env('cookies', null)   // Remove environment cookies
  });

  it('should not have any cookies after logout', () => {...})   // no cookies here
})

As an after-thought, you could divide the tests into three subsections

describe('Auth (e2e)', () => {
    
  describe('loggin in', () => {
    it('should load and redirect to /login', () => {...})  
    it('login button should be disabled initially', () => {...})
    it('login button should be enabled...', () => {...})     
    it('should navigate to the home/dashboard upon logging in', () => {
      cy.get('#btn-login').click();
      ...
      // Save cookies to environment
      cy.getCookies().then(cookies => Cypress.env('cookies', cookies))
    });
  }}

  describe('when logged in', () => {

    beforeEach(() => {
      const cookies = Cypress.env('cookies')   
      cookies.forEach(c => cy.setCookie(c.name, c.value))
    })
    
    it('should have 4 cookies available', () => {...}) 
    it('should have a JwtToken cookie', () => {...})   
  })

  describe('on logging out', () => {
    it('should logout...', () => {
      cy.get('#profile-menu-item-logout').click(); //Logout called here
      ...
    });
    it('should not have any cookies after logout', () => {...})   
  })
})


Answered By - Fody
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to delete cookies on an ASP.NET website

 October 25, 2022     asp.net, c#, cookies, session, session-cookies     No comments   

Issue

In my website when the user clicks on the "Logout" button, the Logout.aspx page loads with code Session.Clear().

In ASP.NET/C#, does this clear all cookies? Or is there any other code that needs to be added to remove all of the cookies of my website?


Solution

Try something like that:

if (Request.Cookies["userId"] != null)
{
    Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);   
}

But it also makes sense to use

Session.Abandon();

besides in many scenarios.



Answered By - Kirill
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] How to set a cookie through CORS

 October 20, 2022     cookies, cross-domain, express, node.js, vue.js     No comments   

Issue

I've reviewed other related posts and none are working for me. I am using vue on the client-side and node on the server-side.

I've tried the suggested method in other posts of using the cors library without success. One would think the below would allow me to send requests from my client localhost:8080 to my server, localhost:3000 but all posts are failing.

const cors = require("cors");
if (process.env.ENV !== "prod") {
  let corsOptions = {
    origin: ["http://localhost:8080"],
    credentials: true,
    optionsSuccessStatus: 200,
  };
  app.use(cors(corsOptions));
}

Here is my controller for setting the cookie.

router.route("/login").post(async (req, res) => {
  //Authenticate users
  const user = await Users.findOne({ where: { email: req.body.email } });

  if (user == null) {
    return res.status(400).send("Cannot find user!");
  }
  try {
    if (await bcrypt.compare(req.body.password, user.password)) {
      const userInfo = {
        username: user.username,
        email: user.email,
        age: user.age,
      };
      const accessToken = generateAccessToken(userInfo);

      const refreshToken = jwt.sign(userInfo, process.env.REFRESH_TOKEN_SECRET);
      res.cookie("token", accessToken, {
        maxAge: 300000,
        secure: true,
        httpOnly: true,
        sameSite: "none",
      });
      res.status(200).send("Logged in!");
    } else {
      res.send("Incorrect email or password!");
    }
  } catch {
    res.status(500).send();
  }
});

Every answer on this site more or less loops back to app.use(cors), for whatever reason it does not work for me.


Solution

I managed to resolve the issue for any who may land here later. I moved up my declaration of cookieparser to above where I initialized my sequelize connection. I also added withCredentials to my axios post. In doing both my cookies are now both setting correctly and are able to be accesssed.

const express = require("express");
require("dotenv").config();
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const cookieParser = require("cookie-parser");
app.use(cookieParser());
const port = process.env.PORT || 8080;
const lib = require("./lib"); //This is all custom functions
const sql = require("./database");
      onSubmit() {
        let loginInfo = {
          email: email.value,
          password: password.value,
        };
        axios
          .post("http://localhost:3000/user/login", loginInfo, {
            withCredentials: true,
          })
          .then(() =>
            $q.notify({
              color: "green-4",
              textColor: "white",
              icon: "cloud_done",
              message: "Account successfully created!",
            })
          )
          .catch(() =>
            $q.notify({
              color: "red-5",
              textColor: "white",
              icon: "warning",
              message: "Email or username already taken!",
            })
          );
      },


Answered By - Daelso
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to share cookie across different domains NodeJS

 October 20, 2022     cookies, javascript, jwt, node.js     No comments   

Issue

I have this return statment in my backend code:

return res
.status(200)
.cookie("auth_token", token, {
  httpOnly: false,
  domain: "domain.com",
  secure: true,
  expires: new Date(Date.now() + (6 * 60 * 60 * 1000))
})
.send({
  data: token,
  code: "100",
  message: `AUTHENTICATION SUCCESS. IP: ${clientIP}, Geo: ${location}, Info: ${
    (app, os)
  }`,
});

which saves a JWT token on domain domain.com, I'd like this to also work with domain2.com, for example, as my authentication system is now used for multiple sites and it runs off of a different domain to domain2.com.

A user goes on site domain.com and that site checks if a auth-token cookie is present, if not it should redirect to a completely different domain auth.domain2.com. This is where the user authenticates; once they have autenticated themselves the above return statment should save the cookie in their browser for ideally domain.com and domain2.com. After, they are redirected back to domain.com for it to then check if the auth-token cookie is present once again, if so, check it's valid, and then allow the user in.

I have tried to just save the cookie for the domain thats not the domain the autenticated code is run on (the code above for example): domain: "domain.com" to domain: "domain2.com" it still will not work/save the cookie for that domain.

Is this possible? If not what are the workarounds?


Solution

Cookies from one domain cannot be accessed from another domain, but this is actually not necessary.

The logon flow that you describe implies for me that you need two cookies:

  1. User visits domain.com and a logon flow starts with a redirection to auth.domain2.com.
  2. User posts their credentials to auth.domain2.com and receives a response that
    • sets a cookie A for domain auth.domain2.com and
    • redirects the browser back to domain.com (with a SAML response or a JWT or an authorization code or something that indicates that the user has successfully logged on).
  3. In response to the request domain.com?SAMLResponse=..., the browser receives a cookie B (a JWT named auth_token in your case) for domain domain.com.

After that, every request that the browser makes to domain.com contains cookie B, which therefore establishes a session with domain.com.

If the user later visits domain3.com (or returns to domain.com after having logged off), a second logon flow to auth.domain2.com is started, but this time, the request to auth.domain2.com contains cookie A. Therefore, auth.domain2.com immediately redirects the browser back to domain3.com, without asking for credentials in step #2 above.

In other words: Cookie A establishes a session with auth.domain2.com, and cookie B establishes a session with domain.com. (And a third cookie C establishes a session with domain3.com in step #3 of the second logon flow.)

This should fulfil your requirements.



Answered By - Heiko Theißen
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 15, 2022

[FIXED] How do I set/unset a cookie with jQuery?

 October 15, 2022     cookies, dom, javascript, jquery     No comments   

Issue

How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?


Solution

Update April 2019

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

Basic examples:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

See the docs on github for details.


Before April 2019 (old)

See the plugin:

https://github.com/carhartl/jquery-cookie

You can then do:

$.cookie("test", 1);

To delete:

$.removeCookie("test");

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

$.cookie("test", 1, { expires : 10 });

If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.

To cover all the options:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

To read back the value of the cookie:

var cookieValue = $.cookie("test");

UPDATE (April 2015):

As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.



Answered By - Alistair Evans
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 13, 2022

[FIXED] How to manage and send httpOnly stored jwt cookies within React and Axios

 October 13, 2022     axios, cookie-httponly, cookies, express, reactjs     No comments   

Issue

I'm actively trying to gain knowledge on httpOnly cookie and found out lots of article on it that why should we use it.

But I haven't seen any practical example of how to work with it. From few trial and error, I came to knew that we can't set httpOnly flag in browser and needed to be done on server. So I, used cookie-parser library accordingly:

const express = require('express');
var cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

app.post('/generateToken', (req, res) => {
    res.cookie('AccessToken', JWT_AUTH_TOKEN, {
        expires: new Date(new Date().getTime() + 30 * 1000),
        sameSite: 'strict',
        httpOnly: true,
        
    })
    res.cookie('RefreshToken', JWT_REFRESH_TOKEN, {
        expires: new Date(new Date().getTime() + 31557600000),
        sameSite: 'strict',
        httpOnly: true,
    }).send("hello")
    
});

app.listen(process.env.PORT || 5050);

By this I successfully get the cookie stored in my browser with all the property like sameSite, HttpOnly except secure:true as I'm on local host. But the problem is as we cant access these httpOnly token with javascript, How do I send it to particular routes with proper header like below

let token = req.headers['authorization'];

and send httpOnly cookie refreshToken to lets say /refresh Route to get new accessTokens with Axios or whats the way of doing it?


Solution

When you have set the cookies with HttpOnly flag, the cookies will be automatically sent via HTTP request from the browser to the server. You don't have to explicitly set it in HTTP Header.

With cors installed at the server, you can access the cookie with req.cookies.

I am not sure with axios, but if using fetch API, we will need to add credential:'include' option in the fetch API, so that the HttpOnly cookies can be set.

Take a look at this post.



Answered By - Sem
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why browser can't set cookies by default

 October 13, 2022     axios, cookies, cross-domain, express, http-headers     No comments   

Issue

I know there are a lot of discussion about this topic already did. and i think i have followed all the instruction but still can't succeed.I think i'm missing something.

Here's my cookie :

 const cookieOptions = {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
    path: '/',
    sameSite: 'lax',
    maxAge: 1000 * 60 * 60 * 1,
  };
  if (process.env.NODE_ENV === 'production') {
    cookieOptions.secure = true;
  }

  res.cookie('jwt', token, cookieOptions);

Cors :

app.use(
  cors({
    origin: ['http://localhost:3000'],
    credentials: true,
  })
);

Frontend :

const { data } = await axios.post(
        "http://127.0.0.1:8000/api/v1/users/login",
        {
          email: enteredEmail,
          password: enteredPassword,
        },
        { withCredentials: true }
      );

I have also used axios.defaults.withCredentials = true; . But still i can't find my jwt in Application > cookies.

Here's my Response header enter image description here

and this is my request header

enter image description here


Solution

"res.cookie()" only set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.If you take a look closely at the response header, see that jwt=... is present in the Set-Cookie header.

For your implementation, where you try to access the data from the axios response, you should look into res.json() or res.send(), as it directly sends the response back in the body, not the header.



Answered By - MTN
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 13, 2022

[FIXED] How to access Cookies cross-device/cross-browser?

 September 13, 2022     cookies, cross-browser, cross-platform     No comments   

Issue

Lets say a user opens website with utm from a third-party ios app with webview - instagramm, facebook.

E.g. example.com?utm_source=facebook&utm_medium=banner&utm_campaign=advertisement1

Javascript on example.com creates a cookie with those campaign details. How can you see those campaign details if a user visits a website from a different device or browser?


Solution

It turned out cookies are saved locally, and cannot be accessed from another device, unless you save them to a database and assign to a user, when he makes an authorization.

So basically if you want to keep cookies cross-device/cross-browser for a user, you should sync them with your user data in database.



Answered By - Sam Tyurenkov
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 7, 2022

[FIXED] Why is jQuery's .ajax() method not sending my session cookie?

 September 07, 2022     ajax, cookies, jquery, session     No comments   

Issue

After logging in via $.ajax() to a site, I am trying to send a second $.ajax() request to that site - but when I check the headers sent using FireBug, there is no session cookie being included in the request.

What am I doing wrong?


Solution

AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.

This may be a Cross Domain Problem.

Maybe you tried to call a url from www.domain-a.com while your calling script was on www.domain-b.com (In other words: You made a Cross Domain Call in which case the browser won't sent any cookies to protect your privacy).

In this case your options are:

  • Write a small proxy which resides on domain-b and forwards your requests to domain-a. Your browser will allow you to call the proxy because it's on the same server as the calling script.
    This proxy then can be configured by you to accept a cookie name and value parameter which it can send to domain-a. But for this to work you need to know the cookie's name and value your server on domain-a wants for authentication.
  • If you're fetching JSON objects try to use a JSONP request instead. jQuery supports these. But you need to alter your service on domain-a so that it returns valid JSONP responds.

Glad if that helped even a little bit.



Answered By - flu
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing