美文网首页
如何获取Cookie?

如何获取Cookie?

作者: 诺之林 | 来源:发表于2018-08-30 18:26 被阅读203次

    目录

    Server

    Startup

    egg-init --type=simple read-cookie-server
    
    cd read-cookie-server && cnpm i
    
    cnpm run dev # localhost:7001
    
    • 测试
    curl localhost:7001 # hi, egg
    

    Router

    vim app/router.js
    
    'use strict';
    
    module.exports = app => {
        const { router, controller } = app;
        router.get('/', controller.home.index);
        router.post('/login', controller.auth.login);
    };
    

    Controller

    vim app/controller/auth.js
    
    'use strict';
    
    const Controller = require('egg').Controller;
    
    class AuthController extends Controller {
        async login() {
            const ctx = this.ctx;
            ctx.session.user = 1;
            ctx.body = { message: 'success' };
            ctx.status = 200;
        }
    }
    
    module.exports = AuthController;
    
    vim config/config.default.js
    
    // 省略了未修改的代码
        config.session = {
            httpOnly: true,
            encrypt: false,
        };
    
        config.security = {
            csrf: {
                enable: false,
            },
        };
    // 省略了未修改的代码
    
    • 测试
    curl -X POST localhost:7001/login # {"message":"success"}
    

    CORS

    cnpm i --save egg-cors
    
    vim config/plugin.js
    
    'use strict';
    
    exports.cors = {
        enable: true,
        package: 'egg-cors',
    };
    
    vim config/config.default.js
    
    // 省略了未修改的代码
        config.cors = {
            credentials: true,
            origin: 'http://localhost:8080',
            allowMethods: 'HEAD,OPTIONS,GET,PUT,POST,DELETE,PATCH',
        };
    // 省略了未修改的代码
    

    关于egg.js更多参考Egg.js实战

    Client

    Startup

    vue create read-cookie-client
    
    cd read-cookie-client && yarn serve
    

    View

    vim src/App.vue
    
    <template>
        <div id="app">
            <div>
                <button v-on:click="login">登录</button>
                <a>{{message}}</a>
            </div>
        </div>
    </template>
    
    <script>
    export default {
        name: 'app',
        data() {
            return {
                message: '',
            }
        },
        methods: {
            login() {
                fetch('http://localhost:7001/login', { method: 'POST', credentials: 'include' })
                    .then(res => {
                        return res.json();
                    }).then(json => {
                        this.message = json;
                    }).catch(error => {
                        this.message = error;
                    });
            },
        }
    }
    </script>
    
    <style>
    </style>
    
    • 测试

    使用浏览器打开http://localhost:8080

    方法1

    我们知道: 浏览器cookie是通过response的set-cookie header实现的 效果如下

    how-to-get-cookie-01.png

    那么是否可以通过fetch api的response获取到cookie呢 代码如下

    vim src/App.vue
    
    // 省略了未修改的代码
        methods: {
            login() {
                fetch('http://localhost:7001/login', { method: 'POST', credentials: 'include' })
                    .then(res => {
                        console.log(res.headers.get('content-type'));
                        console.log(res.headers.get('set-cookie'));
                        return res.json();
                    }).then(json => {
                        this.message = json;
                    }).catch(error => {
                        this.message = error;
                    });
            },
        }
    // 省略了未修改的代码
    

    点击登录按钮后 浏览器console打印结果如下

    how-to-get-cookie-02.png

    为什么fetch api无法获取reponse的set-cookie header呢 解释如下

    更多参考Set-Cookie Response header not in response.headers

    因此我们知道

    方法1: 通过fetch api response获取cookie不可行!

    方法2

    我们知道: 如果cookie的HttpOnly属性设置为false 那么就可以通过document.cookie获取到cookie

    vim src/App.vue
    
    <template>
        <div id="app">
            <div>
                <button v-on:click="login">登录</button>
                <a>{{message}}</a>
            </div>
            <div>
                <button v-on:click="getCookie">获取cookie</button>
                <a>{{cookie}}</a>
            </div>
        </div>
    </template>
    
    <script>
    export default {
        name: 'app',
        data() {
            return {
                message: '',
                cookie: '',
            }
        },
        methods: {
            login() {
                fetch('http://localhost:7001/login', { method: 'POST', credentials: 'include' })
                    .then(res => {
                        console.log(res.headers.get('content-type'));
                        console.log(res.headers.get('set-cookie'));
                        return res.json();
                    }).then(json => {
                        this.message = json;
                    }).catch(error => {
                        this.message = error;
                    });
            },
            getCookie() {
                this.cookie = document.cookie ? document.cookie : '获取失败';
            },
        }
    }
    </script>
    
    <style>
    </style>
    
    • 测试

    使用浏览器打开http://localhost:8080

    点击"登录"后点击"获取cookie" 结果"获取失败" 效果如下

    how-to-get-cookie-03.png

    此时 修改Server代码将HttpOnly设置为false 代码如下

    vim config/config.default.js
    
    // 省略了未修改的代码
        config.session = {
            httpOnly: false,
            encrypt: false,
        };
    // 省略了未修改的代码
    
    • 测试

    使用浏览器打开http://localhost:8080

    点击"登录"后点击"获取cookie"到cookie 效果如下

    how-to-get-cookie-04.png

    但是此时有面临XSS攻击的危害 因此

    方法2: 通过将cookie的HttpOnly属性设置为false获取cookie不可行!

    小结

    关于cookie操作涉及三个主体

    Javascript App <-> Browser <-> Server
    

    安全的cookie设计 基于Browser和Server而非Javascript

    这也正是上述两种方法都无法获取cookie的原因

    参考

    相关文章

      网友评论

          本文标题:如何获取Cookie?

          本文链接:https://www.haomeiwen.com/subject/iyzrwftx.html