The problem:
In production my server and client are running in different origins (CORS).
The client needs to store a cookie sent from the server, but it fails to do so even that the cookie attributes are set as required.
The server is written in Flask and the client sends requests with Axios.
What I've tried so far and current status:
First off, when the client and server are in the same origin (localhost:3000 and localhost:5000) the cookie is set as expected
To simulate CORS locally, I run the client in 127.0.0.1:3000 and the server in localhost:5000.
The bug is reproduced in these settings.
I followed this post (and many others) and configured the server, client and the cookie as required, but still the cookie is not set in the browser
Since this is a cross-origin request, a preflight OPTIONS request is sent first
Current status:
Preflight request headers:
OPTIONS /api/v0/get_csrf_token HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Accept: */*
Access-Control-Request-Method: GET
Access-Control-Request-Headers: app-version,authorization,os-type
Origin: http://127.0.0.1:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Sec-Fetch-Dest: empty
Referer: http://127.0.0.1:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Preflight response headers:
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: HEAD, GET, OPTIONS
Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: app-version, authorization, os-type
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Vary: Origin
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://rawgit.com; connect-src 'self' https://*.fontawesome.com; img-src 'self' data: https://*.amazonaws.com https://*.vizcloud.net https://*.viz.cloud; font-src 'self' https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://fonts.gstatic.com https://*.fontawesome.com; script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://unpkg.com http://d3js.org https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net
X-Content-Security-Policy: default-src https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://rawgit.com; connect-src 'self' https://*.fontawesome.com; img-src 'self' data: https://*.amazonaws.com https://*.vizcloud.net https://*.viz.cloud; font-src 'self' https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://fonts.gstatic.com https://*.fontawesome.com; script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://unpkg.com http://d3js.org https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net
Referrer-Policy: strict-origin-when-cross-origin
Content-Length: 0
Server: Werkzeug/0.16.0 Python/3.7.9
Date: Thu, 13 Jan 2022 09:06:31 GMT
Follow-up GET request headers:
GET /api/v0/get_csrf_token HTTP/1.1
Host: localhost:5000
Connection: keep-alive
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
Authorization: null
Accept: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
os-type: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
sec-ch-ua-platform: "macOS"
app-version: web
Origin: http://127.0.0.1:3000
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://127.0.0.1:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: X-CSRFToken=IjI1ODlkZGQ4MzJlMzRiZDM2M2U5YzgyM2EyODAxNTgxZTIyNDYwOWYi.FMF7UQ.-do_q8Zv3Fonh5QdSvfhaGbAVBk
Follow-up GET response headers:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 3
/*** THIS IS THE COOKIE I NEED TO STORE ***/
Set-Cookie: X-CSRFToken=IjFhYmVkNjZmN2Y0NjEzMTNmNzRhNzI4ZGVlZTVmMzQzNTVjN2JmOTgi.FMF9Fw.DWGaapFRX40GwpV3KU07iHEZzKc; Expires=2022-01-13 12:06:31.906331; SameSite=None; Path=/; Secure
Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Credentials: true
Vary: Origin, Cookie
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://rawgit.com; connect-src 'self' https://*.fontawesome.com; img-src 'self' data: https://*.amazonaws.com https://*.vizcloud.net https://*.viz.cloud; font-src 'self' https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://fonts.gstatic.com https://*.fontawesome.com; script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://unpkg.com http://d3js.org https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net
X-Content-Security-Policy: default-src https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://rawgit.com; connect-src 'self' https://*.fontawesome.com; img-src 'self' data: https://*.amazonaws.com https://*.vizcloud.net https://*.viz.cloud; font-src 'self' https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://fonts.gstatic.com https://*.fontawesome.com; script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://unpkg.com http://d3js.org https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://fonts.googleapis.com https://rawgit.com https://*.fontawesome.com https://cdn.jsdelivr.net
Referrer-Policy: strict-origin-when-cross-origin
Set-Cookie: session=eyJjc3JmX3Rva2VuIjoiMWFiZWQ2NmY3ZjQ2MTMxM2Y3NGE3MjhkZWVlNWYzNDM1NWM3YmY5OCJ9.FMF9Fw.r8g0VeK8PjVqEtWz6ZcJrVYg6fo; HttpOnly; Path=/
Server: Werkzeug/0.16.0 Python/3.7.9
Date: Thu, 13 Jan 2022 09:06:31 GMT
Notice that the X-CSRFToken cookie in the GET response headers has SameSite=None and Secure attributes, as required for CORS.
But when I inspect DevTools in Application -> Storage -> Cookies, I see no cookies set in the browser.
You can also see the responses in the following images:
preflight response headers
GET response headers
What am I missing?
Related
I see this question was answered in many forums and answered in many ways - Most of the Answers are we are doing in the same way.
Still, we see that Set-Cookie is NOT SAVING INTO BROWSER - due to this Keycloak is Not able to recognize the Impersonation Login Session.
Here is the Request (done via Angular)
const url = environment.BASE_URL + 'realms/master/custom/realms/REALM_NAME/users/' + userName + '/impersonation';
const headers = new Headers();
headers.append('Authorization', 'Bearer ' + user.adminToken);
headers.append('Access-Control-Allow-Origin', '*')
const options = new RequestOptions({ method: RequestMethod.Post, headers: headers });
options.withCredentials = true;
return this._http
.post(url, JSON.stringify(representativeDetails), options)
.map((response: Response) => response.json())
.catch(this.handleErrorObservable);
Here is the Response sent from our Java application
return Response.ok(result)
.header(HttpHeaders.CONTENT_TYPE, org.keycloak.utils.MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", CollectionUtil.join(new HashSet(Arrays.asList("GET", "PUT", "POST", "DELETE"))))
.header("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization, Access-Control-Allow-Origin")
.header("Access-Control-Max-Age", 1234)
.header("Access-Control-Allow-Credentials", true)
.header("Access-Control-Expose-Headers", "*")
.build();
Below I copied from my browser where we can see all the Request and Response Headers
Response Headers
access-control-allow-headers: Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization, Access-Control-Allow-Origin
access-control-allow-methods: DELETE, POST, GET, PUT
access-control-allow-origin: https://DOMAINNAME.COM
access-control-expose-headers: *
access-control-max-age: 1234
cache-control: NO-CACHE
content-length: 108
content-type: application/json
date: Fri, 28 Jan 2022 20:31:19 GMT
p3p: CP="This is not a P3P policy!"
pragma: NO-CACHE
referrer-policy: no-referrer
set-cookie: KEYCLOAK_IDENTITY=eyJhbGciOiJIUzI1NiIsInXXXXXXX--------tm_sC4lnc; Version=1; Path=/; SameSite=None; Secure; HttpOnly
set-cookie: KEYCLOAK_IDENTITY_LEGACY=eyJhbGciOiJIUzI1NiIsInXXXXXXX--------tm_sC4lnc; Version=1; Path=/; Secure; HttpOnly
set-cookie: KEYCLOAK_SESSION=REALM_NAME/065ec370-e803-4351-9a06; Version=1; Expires=Mon, 07-Feb-2022 20:31:19 GMT; Max-Age=864000; Path=/; SameSite=None; Secure
set-cookie: KEYCLOAK_SESSION_LEGACY=REALM_NAME/065ec370-e803-4351-9a06; Version=1; Expires=Mon, 07-Feb-2022 20:31:19 GMT; Max-Age=864000; Path=/; Secure
set-cookie: AUTH_SESSION_ID=; Version=1; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0; Path=/; Secure; HttpOnly
set-cookie: KC_RESTART=; Version=1; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0; Path=/; Secure; HttpOnly
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
**Request Headers**
:authority: SSO_BASE_URL.COM
:method: POST
:path: /auth/realms/master/custom/realms/REALM_NAME/users/USER_ID/impersonation
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,hi;q=0.8,en-IN;q=0.7
access-control-allow-origin: *
authorization: Bearer TOKEN_TOKEN_TOKEN
cache-control: no-cache
content-length: 36
content-type: application/json
cookie: AUTH_SESSION_ID=d1d12d09-3;
AUTH_SESSION_ID_LEGACY=d1d12d09-3;
KEYCLOAK_SESSION=master/eda99620-92e2-4;
KEYCLOAK_SESSION_LEGACY=master/eda99620-92e2-4;
KEYCLOAK_IDENTITY=eyJhbGciOiJIUzI1NiI------------; KEYCLOAK_IDENTITY_LEGACY=eyJhbGciOiJIUzI1NiI------------;
LanguageDisplayDirection=ltr;
SplashScreen=false;
cookiebanner=false;
origin: https://DOMAINNAME.COM
pragma: no-cache
referer: https://DOMAINNAME.COM/
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
Here is Keycloak Server Source Code and logic to create the Login Cookie
https://github.com/keycloak/keycloak/blob/main/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java
https://github.com/keycloak/keycloak/blob/main/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java
I'm using Django Rest Framework and Vue.js to build a basic web app, and am currently working on the auth. Using axios to send a post request while registering a new user returns 401 in Chrome for some reason, but works in other browsers (Edge) and returns a 201 Created.
The error in chrome is "detail: Invalid Token", but this particular endpoint (registration) doesn't even need auth/token to access.
My frontend is at http://192.168.1.33:8080 and my backend is at http://127.0.0.1:8000
I am trying to POST data to http://127.0.0.1:8000/api/v1/users/auths/
The Network tab in chrome dev tools after trying a request:
Request URL: http://127.0.0.1:8000/api/v1/users/auths/
Request Method: POST
Status Code: 401 Unauthorized
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: http://192.168.1.33:8080
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 27
Content-Type: application/json
Date: Mon, 06 Dec 2021 12:19:15 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.8.5
Vary: Accept, Origin
WWW-Authenticate: Token
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Token acf8b9099de5eba413dea141ce2c06b6cfb03159
Connection: keep-alive
Content-Length: 53
Content-Type: application/json
Host: 127.0.0.1:8000
Origin: http://192.168.1.33:8080
Referer: http://192.168.1.33:8080/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
The network tab in Edge dev tools after trying the same thing:
Request URL: http://127.0.0.1:8000/api/v1/users/auths/
Request Method: POST
Status Code: 201 Created
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: http://192.168.1.33:8080
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 89
Content-Type: application/json
Date: Mon, 06 Dec 2021 12:20:25 GMT
Location: http://127.0.0.1:8000/api/v1/users/auths/12/
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.8.5
Vary: Accept, Origin, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization
Connection: keep-alive
Content-Length: 51
Content-Type: application/json
Host: 127.0.0.1:8000
Origin: http://192.168.1.33:8080
Referer: http://192.168.1.33:8080/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.43
The obvious difference is that there is a "WWW-Authenticate: Token" in the Chrome Network tab, which is odd.
CORS headers and all have been set up properly, plus the issue is only in Chrome. Is this some Chrome quirk, or am I missing something?
Why is it that, after spending some two hours on a problem, you only get the answer after you've posted it on a forum? Probably something to do with putting the problem down categorically and formally...
Anyway. Turns out the issue was with there being a random token sitting in Chrome's local storage, which was causing all the trouble with the "invalid" token. I cleared local storage, and it's working now. No clue why I had to do this specifically — I had made sure to clear the cache earlier...
I am getting the following response from the Django (2.2) default login view:
Request URL: https://api.n.exchange/en/accounts/login/?next=/en/referrals/
Request Method: GET
Status Code: 200 OK
Remote Address: 104.25.23.99:443
Referrer Policy: no-referrer-when-downgrade
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
CF-RAY: 51105b439e71b50e-VNO
Connection: keep-alive
Content-Encoding: br
Content-Language: en
Content-Type: text/html; charset=utf-8
Date: Wed, 04 Sep 2019 13:37:09 GMT
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Expires: Wed, 04 Sep 2019 13:37:09 GMT
Server: cloudflare
Set-Cookie: csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; expires=Wed, 02 Sep 2020 13:37:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Transfer-Encoding: chunked
Vary: Cookie, Origin
X-Frame-Options: SAMEORIGIN
X-NewRelic-App-Data: PxQGUlFVCwoGR1JTDwQFX1IAFB9AMQYAZBBZDEtZV0ZaCldOdxRdARBfWA9JB1JSXgMOTFReWRIWWFQdAxMXCh4UUQdPSw5+XAJQD2cIVhVKUVIVRE8IHwBKUVAPBw5QVggOBltfUVYDUw5WFBUFHhFVAFAABABbAQEGWFYGWQVSRk0EVl1EAzk=
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,he;q=0.7,lt;q=0.6,de;q=0.5
Connection: keep-alive
Cookie: __cfduid=d76f7b7d2a1caa6948456ad6829dc25991553698344; _ga=GA1.2.2123122031.1553698346; _ym_uid=1553698347983819119; _ym_d=1553698347; crisp-client%2Fsession%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=session_76921095-b26c-4790-a968-82cf111e3940; _hjid=e834477e-35c2-4ef9-aacd-5fb2d644ae2c; crisp-client%2Fsocket%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=1; _gid=GA1.2.1927749960.1567447617; USER_TZ=Europe/Vilnius; django_language=en; _ym_isad=1; _ym_visorc_42222484=w; _ym_visorc_45642111=w; csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; _gat=1
Host: api.n.exchange
Referer: https://api.n.exchange/en/accounts/login/?next=/en/referrals/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
X-NewRelic-ID: VQUAV1VaDhADVVlXBQgBVw==
next: /en/referrals/
As you can clearly see, the set-cookie header for the sessionid which represents the authenticated Django session is missing.
What could be the cause? (at first, I was thinking the reason is that we have a self signed HTTP certificate behind Cloudflare but we have migrated to a valid letsencrypt certificate and removed cloudflare to test it, but the problem persists).
Thanks!
It seems that SESSION_COOKIE_DOMAIN was set to the wrong setting
I'm using Django Rest Framework with CSRF. POST and PUT methods work as expected, but DELETE is giving error 403 with - following message "{"detail":"CSRF Failed: CSRF token missing or incorrect."}.
It appears that frontend application (Angular) is doing a proper POST and PUT requests. I'm not getting any issues with CSRF nor CORS.
Example:
DELETE Request:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pl;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Cookie: _ga=GA1.1.1418236812.1564012825; _gid=GA1.1.747517255.1564126213; sessionid=zho7t6c8vbot46uuwka8ufh53pkanein; _gat_gtag_UA_127399308_1=1;
X-XSRF-TOKEN=hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
Host: 127.0.0.1:4200
http-x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
Origin: http://127.0.0.1:4200
Pragma: no-cache
Referer: http://127.0.0.1:4200/cost_center/form/e503dbfd-8eae-49e4-becc-4aa60016b996
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
DELETE Response headers:
HTTP/1.1 403 Forbidden
X-Powered-By: Express
access-control-allow-origin: http://127.0.0.1:4200
date: Sun, 28 Jul 2019 14:36:12 GMT
server: WSGIServer/0.2 CPython/3.7.3
content-type: application/json
vary: Accept, Origin, Cookie
allow: GET, PUT, DELETE, HEAD, OPTIONS
x-frame-options: SAMEORIGIN
content-length: 58
access-control-allow-credentials: true
connection: keep-alive
DELETE Response:
Request URL: http://127.0.0.1:4200/api/cost_center/e503dbfd-8eae-49e4-becc-4aa60016b996
Request Method: DELETE
Status Code: **403 Forbidden**
Remote Address: 127.0.0.1:4200
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
Then, when I do for example "PUT" request, it is executed without any issue:
PUT Request:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pl;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 82
Content-Type: application/json
Cookie: _ga=GA1.1.1418236812.1564012825; _gid=GA1.1.747517255.1564126213; sessionid=zho7t6c8vbot46uuwka8ufh53pkanein; X-XSRF-TOKEN=hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
Host: 127.0.0.1:4200
http-x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
Origin: http://127.0.0.1:4200
Pragma: no-cache
Referer: http://127.0.0.1:4200/cost_center/form/e503dbfd-8eae-49e4-becc-4aa60016b996
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp
PUT Response Headers:
access-control-allow-credentials: true
access-control-allow-origin: http://127.0.0.1:4200
allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
connection: keep-alive
content-length: 196
content-type: application/json
date: Sun, 28 Jul 2019 14:51:41 GMT
server: WSGIServer/0.2 CPython/3.7.3
vary: Accept, Origin, Cookie
x-frame-options: SAMEORIGIN
X-Powered-By: Express
PUT Response:
Request URL: http://127.0.0.1:4200/api/cost_center/e503dbfd-8eae-49e4-becc-4aa60016b996
Request Method: PUT
Status Code: **200 OK**
Remote Address: 127.0.0.1:4200
Referrer Policy: no-referrer-when-downgrade
You can see that same token has been used in DELETE and PUT, but for some reasons, only PUT works as expected.
It is working OK for POST as well. Again, I'm only having issues with DELETE.
Thank you very much for your help.
urls.py file:
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import CostCenterViewSet
cost_center_list = CostCenterViewSet.as_view({
'get': 'list',
'post': 'create'
})
cost_center_detail = CostCenterViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
urlpatterns = format_suffix_patterns([
path('', cost_center_list, name='cost-center-list'),
path('<uuid:pk>', cost_center_detail, name='cost-center-detail'),
])
views.py file:
class CostCenterViewSet(viewsets.ModelViewSet):
authentication_classes = [ SessionAuthentication ]
permission_classes = [ IsAuthenticated ]
filter_backends = [ SameCompanyFilterBackend, filters.SearchFilter ]
search_fields = [ 'name', 'owner__first_name', 'owner__last_name', 'owner__email' ]
ordering_fields = ['name', 'owner']
serializer_class = CostCenterSerializer
def get_queryset(self):
return CostCenter.objects.all().order_by('name')
def perform_create(self, serializer):
company = UserProfile.objects.get( user=self.request.user ).company
serializer.save(company=company)
return
I'm expecting, that POST, PUT and DELETE work as in same way properly using CSRF.
Recorded Log-
Response headers:
HTTP/1.1 302 Moved Temporarily
Server: FISServer
Cache-Control: no-cache,no-store,max-age=0
Content-Type: text/html;charset=UTF-8
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; block-all-mixed-content
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Thu, 08 Mar 2018 06:39:57 GMT
Location: https://temp1.temp2.com/pta/pages/index.jsp?st=J6UV- D0EU-5TPE-7H5S-18ZA-TLAT-UVM7-5J4Z
Reply Log-
Response headers:
HTTP/1.1 200 OK
Server: FISServer
Cache-Control: no-store, no-cache, must-revalidate
Content-Type: text/html;charset=UTF-8
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; block-all-mixed-content
Strict-Transport-Security: max-age=31536000; includeSubDomains
Date: Thu, 08 Mar 2018 07:23:35 GMT
Expires: Wed, 31 Dec 1969 23:59:59 GMT
Why am I not getting the Location header in reply log jmeter -> Tried Redirect Auto and Follow Redirects
I am not able to extract st value using RE extractor ->tried searching in response headers
you most probably didn’t variabilize some id which can be in:
header/cookie
url parameter
body of request
As a consequence you don’t get the successful response with 302, and instead get another response with code 200.
I suppose it’s a login screen you’re replaying.
Another possibility is missing Cookie Manager which ypu need to add with standard policy.