クライアントにてaxiosを利用しクロスドメインとしてホストと異なるサーバへリクエストのやり取りをしようとしています。
ログインのリクエストにてサーバ側からはSet-Cookieが入ったレスポンスがやってきていることをブラウザで確認しています。
しかし、その後のリクエストにて、ヘッダーにCookieが入りません。
下記のIssueリンクのようにwithCredentials: true
をクライアント側に設定し、res.header("Access-Control-Allow-Credentials", true);
の設定をNode.jsのサーバ側でも設定してますが、Cookie付きのリクエストをクロスドメインのサーバ側に送信できない状況です。
https://github.com/axios/axios/issues/876
どのようにすればCookieをサーバ側へ送信できるのかご教授願いたいです。
環境
OS: macOS Sierra 10.12.1
ブラウザ: Chrome バージョン: 67.0.3396.87
ソースコードは下記のようになります。
クライアント側 (localhost:9000)
axios.defaults.withCredentials = true; axios.post('http://localhost:3000/sessionLogin', { idToken: idToken }).then(function (response) { console.log(response) // Set-Cookieがブラウザで確認できる axios.get('http://localhost:3000/profile', { // リクエストにCookieがセットされない }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }) }).catch(function (error) { console.log(error) })
サーバ側 (localhost:3000)
var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cookieParser()); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', req.headers['origin']); res.header("Access-Control-Allow-Credentials", true); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.post('/sessionLogin', (req, res) => { // Get the ID token passed and the CSRF token. const idToken = req.body.idToken.toString(); // Set session expiration to 5 days. const expiresIn = 60 * 60 * 24 * 5 * 1000; admin.auth().createSessionCookie(idToken, {expiresIn}).then((sessionCookie) => { // Set cookie policy for session cookie. const options = {domain: 'localhost', maxAge: expiresIn, httpOnly: true, secure: true}; res.cookie('session', sessionCookie, options); res.end(JSON.stringify({status: 'success'})); }, error => { res.status(401).send('UNAUTHORIZED REQUEST!'); }); }); // Whenever a user is accessing restricted content that requires authentication. app.get('/profile', (req, res) => { const sessionCookie = req.cookies.session || ''; // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. if (sessionCookie === '') { console.log('No sessionCookie...'); } else { console.log(sessionCookie); } admin.auth().verifySessionCookie( sessionCookie, true /** checkRevoked */).then((decodedClaims) => { res.end(JSON.stringify({profile: 'Your profile is here!!!'})); }).catch(error => { }); });
回答1件
あなたの回答
tips
プレビュー