未经授权的访问:api令牌Vue到烧瓶

时间:2016-12-05 08:42:18

标签: python api flask token vue.js

我有这个文件:

from flask import render_template, redirect, url_for, g
from flask_httpauth import HTTPTokenAuth
from app import app, db
from .models import User
import json

auth = HTTPTokenAuth(scheme='Token')

tokens = {
    'secret-token-1': 'John',
    'secret-token-2': 'Susan'
}

@auth.verify_token
def verify_token(token):
    print token
    if token in tokens:
        g.current_user = tokens[token]
        return True
    return False

@app.route('/')
@auth.login_required
def index():
    print 'Hello %s!' % g.current_user
    return render_template('show_form.html',
                           title='Vue Request')

@app.route('/api/name', methods=['GET'])
@auth.login_required
def get_name():
    users = User.query.all()
    names = []
    for user in users:
        names.append(user.name)
    return json.dumps(names)

而且,我有这个调用api的Vue JS文件,但我无法获得授权:

Vue.component('name-list', {

    props: ['list'],

    template: `
                <div class="content">
                    <label class="label"> Names: </label>
                    <ul>
                        <task v-for="name in list" v-text="name"></task>
                    </ul>
                </div>
            `

});

Vue.component('task', {

    template: `
                <li><slot></slot></li>
            `

});

new Vue({

    el: '#root',

    http: {
        root: 'http://127.0.0.1:5000',
        headers: {
            Authorization: 'Token secret-token-1'
        }
    },

    data: {
        newName: '',
        nameList: []
    },

    methods: {
        addName(){
            this.nameList = this.nameList.concat(this.newName);
            var name = this.newName;
            this.newName = '';

            this.$http.post('/api/name/'+name).then((response) => {
                console.log(response.message);
            });
        }
    },

    mounted(){
        this.$http.get('/api/name').then((response) => {
            this.nameList= this.nameList.concat(JSON.parse(response.body));
            console.log(this.nameList);
        });
    }


});

我可以使用curl请求访问api:

curl -v -H "Authorization: Token secret-token-1" 127.0.0.1:5000

curl -v -H "Authorization: Token secret-token-1" 127.0.0.1:5000/api/name

但是,我如何直接从VueJS请求中授权...任何帮助?

1 个答案:

答案 0 :(得分:0)

您可以使用config

设置http标头
 // where populate secret-token-1 from cookies or available web resources
Vue.http.headers.common['Authorization'] = 'Token secret-token-1';

如果您使用vue-resource,它会为每个请求发送标头 用于发送特定请求的标头,

  this.$http.get('/api/name', function(node) {
   //  handle response
  }, {headers: {'Authorization': 'Token secret-token-1'}});

注意:使用像get_authtoken这样的常用函数,其中我对令牌进行了硬编码:)