Django - check cookies's "SameSite" attribute - python-3.x

In my Django application, I want to check if a specific cookies has "SameSite=None" or not.
I'm using this code to read the value of the cookies,
cookiesid = request.COOKIES["cookiesid"]
However, I don't know how to check "SameSite" attribute, seems there is no method to check it by request.COOKIES[""]
How can I check it?
I'm using Python 3.6.9 and Django 3.1

I've also been having issues with cross-domain Cookies recently, and I've tracked it down to Google Chrome gradually rolling out their security update that forces the SameSite attribute to Lax if it isn't set
Lax means that the Cookie is going to be blocked cross-domain by default on Google Chrome
Given that you're inspecting the Cookie's attributes in the code, I think that if the SameSite attribute isn't there, than you're not setting it and therefore Google Chrome is forcing the attribute to Lax
As you've stated you're using Django 3.1, the following four entries in your settings.py file might resolve your issue (as it did for me):
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
Good luck!

Going a little bit deeper.
In production set:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
Do not set any of the above flags in development. It will say that cannot set the cookie with SameSite=None if the connection is NOT secure.
Also make sure that you have Django 3, in Django 2 there is a bug and it will output a ValueError.

Related

Current way of setting language in browsers?

I've been searching for a while about the recommended and current way of creating Watir::Browser.new for :chrome and set it to accept a certain language. However, this seems to be a topic with little interest, seems to be ever changing, etc.
So, please, can someone explain what the current and recommended way of setting Chrome's language is?
I'm not talking about Chrome's user interface but the Accept-Language HTTP header that later gets sent with the HTTP request so that an application can render it's web UI using the correct locale and language.
For Firefox this works but I have no luck for Chrome:
profile = Selenium::WebDriver::Firefox::Profile.new
profile["intl.accept_languages"] = "ES"
caps = Selenium::WebDriver::Remote::Capabilities.firefox(firefox_profile: profile)
caps.platform = "Linux"
caps.version = 20
browser = Watir::Browser.new :firefox, :desired_capabilities => caps
Thanks.
The "intl.accept_languages" is a Chrome preference, so can be passed in as:
Watir::Browser.new :chrome, options: {prefs: {'intl' => {'accept_languages' => 'ES'}}}

libtorrent disable dht and lsd in the session

We are creating libtorrent session like this:
ses_settings = lt.session_settings()
ses_settings.ignore_limits_on_local_network = False
ses_settings.announce_to_all_trackers = True
ses_settings.ssl_listen = 0
ses = lt.session()
ses.listen_on(LISTEN_ON_RANGE_START, LISTEN_ON_RANGE_END)
ses.set_settings(ses_settings)
ses.set_download_rate_limit(download_rate)
ses.set_upload_rate_limit(upload_rate)
Similar to ssl_listen, we want to disable DHT, LSD, UPnP, NAT-PMP in the libtorrent session. Is there any way to do it ?
Also in the libtorrent manual page its mentioned as:
Configuration options can be updated after the session is started by calling apply_settings(). Some settings are best set before starting the session though, like listen_interfaces, to avoid race conditions. If you start the session with the default settings and then immediately change them, there will still be a window where the default settings apply.
Changing the settings may trigger listen sockets to close and re-open and NAT-PMP, UPnP updates to be sent. For this reason, it's typically a good idea to batch settings updates into a single call.
How to do the batch setting updates in a single call ?
Basically we want to change these default setting fields: enable_lsd, enable_dht, enable_upnp, enable_natpmp and then create a session object with these settings.
the session_settings type and set_settings() function on session are deprecated (and have been for quite a while). The reference documentation online (https://libtorrent.org) is for the most recent stable release, so you won't find them documented there.
Instead, use settings_pack and apply_settings() on the session. Or even better, pass in your settings pack to the session constructor.
In the C++ interface, settings_pack is a class with a fairly simple interface, but in the python binding it's just a plain dictionary.
To set up a settings pack in python, you do this:
sett = {'enable_lsd': False,
'enable_dht': False,
'enable_upnp': False,
'enable_natpmp': False,
'listen_interfaces': '0.0.0.0:%s' % LISTEN_ON_RANGE_START,
'download_rate_limit': download_rate,
'upload_rate_limit': upload_rate,
'announce_to_all_tracker': True}
ses = lt.session(sett)
# ...
You'll find all the available settings in the reference documentation.

Thorntail MP JWT / Undertow: required authentication

I'm trying to set up a JAX-RS-service in thorntail with JWT authentication. Everything works fine (I can inject Principal and user is correctly set), except that in case of a failed authentication, answer is still sent without any 401-HTTP-Header. What I've done is:
Added #LoginConfig(authMethod = "MP-JWT", realmName = "my-domain") to my Application-Class
Configured the security-domain
security:
security-domains:
my-domain:
jaspi-authentication:
login-module-stacks:
roles-token-stack:
login-modules:
jwt-jaspi-login-module:
code: org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas.JWTLoginModule
flag: required
auth-modules:
http:
code: org.wildfly.extension.undertow.security.jaspi.modules.HTTPSchemeServerAuthModule
module: org.wildfly.extension.undertow
flag: required
login-module-stack-ref: roles-token-stack
Configured JWT-specific things (seem to work, so I'm skipping this here)
What else do I need to do in order for this to work properly? Do I need to add any annotations to my Endpoint? As I said, I want to return a 401 in case of a failed authentication.
What I've found out so far: JASPICAuthenticationMechanism.isMandatory needs to return true in order for this to work. If this is the case JWTAuthMechanism.sendChallenge is triggered after a failure of JWTAuthMechanism.authenticate and so a 401 is sent to the client. But i have no idea, in which cases isMandatory returns true.
Thanks for any help in this case!
One, the configuration of the security domain isn't 100% correct. Here's a fix for one part of the YAML:
roles-token-stack:
login-modules:
- login-module: jwt-jaspi-login-module
code: org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas.JWTLoginModule
flag: required
Two, indeed you need to use the common Java EE annotations (#RolesAllowed, #DenyAll, #PermitAll) on the JAX-RS resources.
Solution (thanks to Ladicek, see comments below):
If you want to use MP JWT, don't start it with Swarm and don't forget to set flag useUberJar if starting it with thorntail:run.

Trouble upgrading to new ember-simple-auth

G'day all,
I've been having trouble upgrading to a more recent version of the ember-simple-auth module.
In particular I seem to have two challenges:
1) the application no longer transitions to the desired route after authenticating. the configuration looks like this:
ENV['ember-simple-auth'] = {
crossOriginWhiteList: ['http://10.10.1.7:3000'],
routeAfterAuthentication: 'profile',
//store: 'simple-auth-session-store:local-storage',
//authorizer: 'simple-auth-authorizer:token',
};
but it never gets to "profile".
2) I can't get the authenticated session to stick after a reload. I had been trying to use the local-store which I believed would do the trick, but it's not. Has something changed in the implementation?
The documentation seems to indicate that the configuration strings are right, but the transition and session store don't seem to be working.
Has anyone had a similar problem?
Thanks,
Andrew
you could try adding "routeIfAlreadyAuthenticated" to ENV['ember-simple-auth'] - or you could transition manually in index route "afterModel" hook, if session is already authenticated
have you configured a session store? https://github.com/simplabs/ember-simple-auth#session-stores - the way it's configured changed in 1.0, now you can add the desired session store to app/session-stores/application.js - maybe this solves #1 too.
OK. As the comments call out, there were two problems here:
1) I had written a customer authorizer for the old version of simple-auth which didn't work with the new version, and
2) I had a typo in the adapter code, where DataAdapterMixin was DAtaAdapterMixin.
Removing (1) and fixing (2) fixed the problem.

wsgi cookies - no middleware

Sounds simple enough
def create_cookie():
bag = string.ascii_uppercase + string.ascii_lowercase + string.digits
cookie = Cookie.SimpleCookie()
cookie['sessionid'] = ''.join(random.sample(bag,24))
cookie['sessionid']['expires'] = 600
return 'Set-Cookie: ', cookie.output().replace('Set-Cookie: ', '', 1)
cookie.output() is Set-Cookie: sessionid=YmsrvCMFapXk6wAt4EVKz2uU; expires=Sun, 14-Aug-2011 21:48:19 GMT
headers.append(('Content-type', 'text/html'))
headers.append(('Content-Length', str(output_len)))
headers.append(create_cookie)
This is my response
('200 OK', [('Content-type', 'text/html'), ('Content-Length', '1204'), ('Set-Cookie', 'sessionid=YmsrvCMFapXk6wAt4EVKz2uU; expires=Sun, 14-Aug-2011 21:48:19 GMT')], 'html stuff')
This is what I get from envirion:
HTTP_COOKIE: sessionid=YmsrvCMFapXk6wAt4EVKz2uU
And when I click another link on my page, no more HTTP_COOKIE
Using the chrome dev console I can see the request cookie and the page header contains:
Cookie:: sessionid=YmsrvCMFapXk6wAt4EVKz2uU
Now, this bothers me a bit. First of all why does it have double :: ? I tried using 'Set-Cookie' instead of 'Set-Cookie: ' in the create_cookie function. Doing that I didn't get any HTTP_COOKIE at all from environ.
So after lots of searching in the web and everyone just talking middleware (don't suggest I use one please - I'm doing this to learn the wsgi) ... I've come up empty.
Invisible default behavior ftw...
After some intensive debugging I noticed that the following request didn't include the HTTP_COOKIE making it conclusively a problem on the browsers side of actually sending the cookie that I could find in the browser otherwise.
Some digging around revealed that the default path and domain behavior was spoiling my efforts , the difference between /action/login (where the cookie was set) and /display/data (where the cookie wasn't sent was fixed by setting the path in this case to '/'.
"yay"
you could try:
return [tuple(line.split(': ',1)) for line in cookie.output().split('\r\n')]
This also works for multiple entries in cookie.
Of course, you need to use extend instead of append:
headers.extend(create_cookie())

Resources