await axios.get("http://localhost:8000/get_csrf_token/").then((res)=>{ console.log(res.data.csrf_token); axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post('http://localhost:8000/login/',{ username:'admin', password:'Kv79NExi' }, { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': res.data.csrf_token, } }) .then((response) => { log("response login",response.data); }); }); I am trying to access django login from command line script(jest) not browser, however it shows the error like this, <p>Reason given for failure:</p>\n' + ' <pre>\n' + ' CSRF cookie not set.\n' + ' </pre>\n' + It returns 403 error, it looks like sending csrf_token correctly. Where am I wrong? Ran all test suites matching /TopPage/i. node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ AxiosError { message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: [ 'xhr', 'http', 'fetch' ], transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFTOKEN', maxContentLength: -1, maxBodyLength: -1, env: { FormData: [Function: FormData] { LINE_BREAK: '\r\n', DEFAULT_CONTENT_TYPE: 'application/octet-stream' }, Blob: [class Blob] }, validateStatus: [Function: validateStatus], headers: Object [AxiosHeaders] { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v', 'User-Agent': 'axios/1.7.9', 'Content-Length': '42', 'Accept-Encoding': 'gzip, compress, deflate, br' }, withCredentials: true, method: 'post', url: 'http://localhost:8000/login/', data: '{"username":"admin","password":"Kv79NExi"}' }, request: <ref *1> ClientRequest { _events: [Object: null prototype] { abort: [Function (anonymous)], aborted: [Function (anonymous)], connect: [Function (anonymous)], error: [Function (anonymous)], socket: [Function (anonymous)], timeout: [Function (anonymous)], finish: [Function: requestOnFinish] }, _eventsCount: 7, _maxListeners: undefined, outputData: [], outputSize: 0, writable: true, destroyed: false, _last: true, chunkedEncoding: false, shouldKeepAlive: false, maxRequestsOnConnectionReached: false, _defaultKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, strictContentLength: false, _contentLength: '42', _hasBody: true, _trailer: '', finished: true, _headerSent: true, _closed: false, socket: <ref *2> Socket { connecting: false, _hadError: false, _parent: null, _host: 'localhost', _closeAfterHandlingError: false, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, constructed: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: true, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, dataEmitted: true, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Function: onReadableStreamEnd], free: [Function: onFree], close: [ [Function: onClose], [Function: socketCloseListener] ], timeout: [Function: onTimeout], agentRemove: [Function: onRemove], error: [Function: socketErrorListener], finish: [Function: bound onceWrapper] { listener: [Function: destroy] } }, _eventsCount: 7, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: true, needDrain: false, ending: true, ended: true, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 1, constructed: true, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: true, errored: null, closed: false, closeEmitted: false, [Symbol(kOnFinished)]: [] }, allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Circular *1], [Symbol(async_id_symbol)]: 969, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, [Symbol(owner_symbol)]: [Circular *2] }, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: true, [Symbol(kSetKeepAliveInitialDelay)]: 60, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 }, _header: 'POST /login/ HTTP/1.1\r\n' + 'Accept: application/json, text/plain, */*\r\n' + 'Content-Type: application/json\r\n' + 'X-CSRFToken: 9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v\r\n' + 'User-Agent: axios/1.7.9\r\n' + 'Content-Length: 42\r\n' + 'Accept-Encoding: gzip, compress, deflate, br\r\n' + 'Host: localhost:8000\r\n' + 'Connection: close\r\n' + '\r\n', _keepAliveTimeout: 0, _onPendingData: [Function: nop], agent: Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog] }, _eventsCount: 2, _maxListeners: undefined, defaultPort: 80, protocol: 'http:', options: [Object: null prototype] { noDelay: true, path: null }, requests: [Object: null prototype] {}, sockets: [Object: null prototype] { 'localhost:8000:': [ <ref *2> Socket { connecting: false, _hadError: false, _parent: null, _host: 'localhost', _closeAfterHandlingError: false, _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 7, _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Circular *1], [Symbol(async_id_symbol)]: 969, [Symbol(kHandle)]: [TCP], [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: true, [Symbol(kSetKeepAliveInitialDelay)]: 60, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 } ] }, freeSockets: [Object: null prototype] {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: 'lifo', maxTotalSockets: Infinity, totalSocketCount: 1, [Symbol(kCapture)]: false }, socketPath: undefined, method: 'POST', maxHeaderSize: undefined, insecureHTTPParser: undefined, path: '/login/', _ended: true, res: IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: true, endEmitted: true, reading: false, constructed: true, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: true, autoDestroy: true, destroyed: true, errored: null, closed: true, closeEmitted: true, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: true, dataEmitted: true, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [ [Function: responseOnEnd], [Function: handleStreamEnd] ], error: [Function: handleStreamError], data: [Function: handleStreamData], aborted: [Function: handlerStreamAborted] }, _eventsCount: 4, _maxListeners: undefined, socket: <ref *2> Socket { connecting: false, _hadError: false, _parent: null, _host: 'localhost', _closeAfterHandlingError: false, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, constructed: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: true, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, dataEmitted: true, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Function: onReadableStreamEnd], free: [Function: onFree], close: [ [Function: onClose], [Function: socketCloseListener] ], timeout: [Function: onTimeout], agentRemove: [Function: onRemove], error: [Function: socketErrorListener], finish: [Function: bound onceWrapper] { listener: [Function: destroy] } }, _eventsCount: 7, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: true, needDrain: false, ending: true, ended: true, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 1, constructed: true, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: true, errored: null, closed: false, closeEmitted: false, [Symbol(kOnFinished)]: [] }, allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Circular *1], [Symbol(async_id_symbol)]: 969, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, [Symbol(owner_symbol)]: [Circular *2] }, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: true, [Symbol(kSetKeepAliveInitialDelay)]: 60, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, rawHeaders: [ 'date', 'Fri, 06 Dec 2024 19:03:51 GMT', 'server', 'uvicorn', 'content-type', 'text/html; charset=utf-8', 'x-frame-options', 'DENY', 'content-length', '3092', 'vary', 'origin', 'x-content-type-options', 'nosniff', 'referrer-policy', 'same-origin', 'connection', 'close' ], rawTrailers: [], aborted: false, upgrade: false, url: '', method: null, statusCode: 403, statusMessage: 'Forbidden', client: <ref *2> Socket { connecting: false, _hadError: false, _parent: null, _host: 'localhost', _closeAfterHandlingError: false, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: [], flowing: true, ended: false, endEmitted: false, reading: true, constructed: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, errorEmitted: false, emitClose: false, autoDestroy: true, destroyed: false, errored: null, closed: false, closeEmitted: false, defaultEncoding: 'utf8', awaitDrainWriters: null, multiAwaitDrain: false, readingMore: false, dataEmitted: true, decoder: null, encoding: null, [Symbol(kPaused)]: false }, _events: [Object: null prototype] { end: [Function: onReadableStreamEnd], free: [Function: onFree], close: [ [Function: onClose], [Function: socketCloseListener] ], timeout: [Function: onTimeout], agentRemove: [Function: onRemove], error: [Function: socketErrorListener], finish: [Function: bound onceWrapper] { listener: [Function: destroy] } }, _eventsCount: 7, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: true, needDrain: false, ending: true, ended: true, finished: false, destroyed: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 1, constructed: true, prefinished: false, errorEmitted: false, emitClose: false, autoDestroy: true, errored: null, closed: false, closeEmitted: false, [Symbol(kOnFinished)]: [] }, allowHalfOpen: false, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Circular *1], [Symbol(async_id_symbol)]: 969, [Symbol(kHandle)]: TCP { reading: true, onconnection: null, [Symbol(owner_symbol)]: [Circular *2] }, [Symbol(lastWriteQueueSize)]: 0, [Symbol(timeout)]: null, [Symbol(kBuffer)]: null, [Symbol(kBufferCb)]: null, [Symbol(kBufferGen)]: null, [Symbol(kCapture)]: false, [Symbol(kSetNoDelay)]: true, [Symbol(kSetKeepAlive)]: true, [Symbol(kSetKeepAliveInitialDelay)]: 60, [Symbol(kBytesRead)]: 0, [Symbol(kBytesWritten)]: 0 }, _consuming: false, _dumped: false, req: [Circular *1], responseUrl: 'http://localhost:8000/login/', redirects: [], [Symbol(kCapture)]: false, [Symbol(kHeaders)]: { date: 'Fri, 06 Dec 2024 19:03:51 GMT', server: 'uvicorn', 'content-type': 'text/html; charset=utf-8', 'x-frame-options': 'DENY', 'content-length': '3092', vary: 'origin', 'x-content-type-options': 'nosniff', 'referrer-policy': 'same-origin', connection: 'close' }, [Symbol(kHeadersCount)]: 18, [Symbol(kTrailers)]: null, [Symbol(kTrailersCount)]: 0 }, aborted: false, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, reusedSocket: false, host: 'localhost', protocol: 'http:', _redirectable: Writable { _writableState: WritableState { objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: true, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function: bound onwrite], writecb: null, writelen: 0, afterWriteTickInfo: null, buffered: [], bufferedIndex: 0, allBuffers: true, allNoop: true, pendingcb: 0, constructed: true, prefinished: false, errorEmitted: false, emitClose: true, autoDestroy: true, errored: null, closed: false, closeEmitted: false, [Symbol(kOnFinished)]: [] }, _events: [Object: null prototype] { response: [Function: handleResponse], error: [Function: handleRequestError], socket: [Function: handleRequestSocket] }, _eventsCount: 3, _maxListeners: undefined, _options: { maxRedirects: 21, maxBodyLength: Infinity, protocol: 'http:', path: '/login/', method: 'POST', headers: [Object: null prototype] { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v', 'User-Agent': 'axios/1.7.9', 'Content-Length': '42', 'Accept-Encoding': 'gzip, compress, deflate, br' }, agents: { http: undefined, https: undefined }, auth: undefined, family: undefined, beforeRedirect: [Function: dispatchBeforeRedirect], beforeRedirects: { proxy: [Function: beforeRedirect] }, hostname: 'localhost', port: '8000', agent: undefined, nativeProtocols: { 'http:': { _connectionListener: [Function: connectionListener], METHODS: [Array], STATUS_CODES: [Object], Agent: [Function], ClientRequest: [Function: ClientRequest], IncomingMessage: [Function: IncomingMessage], OutgoingMessage: [Function: OutgoingMessage], Server: [Function: Server], ServerResponse: [Function: ServerResponse], createServer: [Function: createServer], validateHeaderName: [Function: __node_internal_], validateHeaderValue: [Function: __node_internal_], get: [Function: get], request: [Function: request], setMaxIdleHTTPParsers: [Function: setMaxIdleHTTPParsers], maxHeaderSize: [Getter], globalAgent: [Getter/Setter] }, 'https:': { Agent: [Function: Agent], globalAgent: [Agent], Server: [Function: Server], createServer: [Function: createServer], get: [Function: get], request: [Function: request] } }, pathname: '/login/' }, _ended: true, _ending: true, _redirectCount: 0, _redirects: [], _requestBodyLength: 42, _requestBodyBuffers: [], _onNativeResponse: [Function (anonymous)], _currentRequest: [Circular *1], _currentUrl: 'http://localhost:8000/login/', [Symbol(kCapture)]: false }, . . . data: '\n' + '<!DOCTYPE html>\n' + '<html lang="en">\n' + '<head>\n' + ' <meta http-equiv="content-type" content="text/html; charset=utf-8">\n' + ' <meta name="robots" content="NONE,NOARCHIVE">\n' + ' <title>403 Forbidden</title>\n' + ' <style type="text/css">\n' + ' html * { padding:0; margin:0; }\n' + ' body * { padding:10px 20px; }\n' + ' body * * { padding:0; }\n' + ' body { font:small sans-serif; background:#eee; color:#000; }\n' + ' body>div { border-bottom:1px solid #ddd; }\n' + ' h1 { font-weight:normal; margin-bottom:.4em; }\n' + ' h1 span { font-size:60%; color:#666; font-weight:normal; }\n' + ' #info { background:#f6f6f6; }\n' + ' #info ul { margin: 0.5em 4em; }\n' + ' #info p, #summary p { padding-top:10px; }\n' + ' #summary { background: #ffc; }\n' + ' #explanation { background:#eee; border-bottom: 0px none; }\n' + ' </style>\n' + '</head>\n' + '<body>\n' + '<div id="summary">\n' + ' <h1>アクセス禁止 <span>(403)</span></h1>\n' + ' <p>CSRF検証に失敗したため、リクエストは中断されました。</p>\n' + '\n' + '\n' + ' <p>このメッセージが表示されている理由は、このサイトはフォーム送信時にCSRFクッキーを必須としているためです。このクッキーはセキュリティ上の理由(使用中のブラウザが第三者によってハイジャックされていないことを確認するため)で必要です。</p>\n' + ' <p>もしブラウザのクッキーを無効に設定しているならば、same-originリクエストのために少なくともこのサイトでは再度有効にしてください。</p>\n' + '\n' + '</div>\n' + '\n' + '<div id="info">\n' + ' <h2>Help</h2>\n' + ' \n' + ' <p>Reason given for failure:</p>\n' + ' <pre>\n' + ' CSRF cookie not set.\n' + ' </pre>\n' + ' \n' + '\n' + ' <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when\n' + ' <a\n' + ' href="https://docs.djangoproject.com/en/4.2/ref/csrf/">Django’s\n' + ' CSRF mechanism</a> has not been used correctly. For POST forms, you need to\n' + ' ensure:</p>\n' + '\n' + ' <ul>\n' + ' <li>Your browser is accepting cookies.</li>\n' + '\n' + ' <li>The view function passes a <code>request</code> to the template’s <a\n' + ' href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>\n' + ' method.</li>\n' + '\n' + ' <li>In the template, there is a <code>{% csrf_token\n' + ' %}</code> template tag inside each POST form that\n' + ' targets an internal URL.</li>\n' + '\n' + ' <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use\n' + ' <code>csrf_protect</code> on any views that use the <code>csrf_token</code>\n' + ' template tag, as well as those that accept the POST data.</li>\n' + '\n' + ' <li>The form has a valid CSRF token. After logging in in another browser\n' + ' tab or hitting the back button after a login, you may need to reload the\n' + ' page with the form, because the token is rotated after a login.</li>\n' + ' </ul>\n' + '\n' + ' <p>You’re seeing the help section of this page because you have <code>DEBUG =\n' + ' True</code> in your Django settings file. Change that to <code>False</code>,\n' + ' and only the initial error message will be displayed. </p>\n' + '\n' + ' <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>\n' + '</div>\n' + '\n' + '</body>\n' + '</html>\n' }, status: 403 } Continue reading...