如何让用户使用HTTP认证登录保护的烧瓶REST的API在Angularjs? [英] How to allow users to login protected flask-rest-api in Angularjs using HTTP Authentication?

查看:172
本文介绍了如何让用户使用HTTP认证登录保护的烧瓶REST的API在Angularjs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。如果我的问题是不明确的,请在下面发表评论。

在瓶中+ angularjs REST API的基本HTTP认证

我只是想登录到angularjs烧瓶-REST的API,我不知道如何发送的登录信息(用户名和密码),烧瓶REST的API。在这个应用程序有一个表后成功登录,它会加载数据。在这里,我们的不使用任何资料库,但用户名和密码的硬$ C $休息服务器code 光盘。和用户名=admin和密码=1234。什么时候可以修改,更新,addNewData。我把这个从这个博客,在这里,他们使用的是淘汰赛,我试图在Angularjs

登录表单

 < D​​IV ID =登录级=模式隐藏变脸的tabindex == 1的角色=对话框中的咏叹调-labelledby =loginLabelARIA隐藏=真正的>
        < D​​IV CLASS =模头>
            < H3 ID =loginLabel>登录< / H3 GT&;
        < / DIV>
        < D​​IV CLASS =模体>
            <窗​​体类=形横>
                < D​​IV CLASS =控制组>
                    <标签类=控制标签为=inputUsername>用户名和LT; /标签>
                    < D​​IV CLASS =控制>
                        <输入NG模型=用户名类型=文本ID =inputUsername占位符=用户名>
                    < / DIV>
                < / DIV>
                < D​​IV CLASS =控制组>
                    <标签类=控制标签为=控件inputPassword>密码和LT; /标签>
                    < D​​IV CLASS =控制>
                        <输入NG模型=密码TYPE =密码ID =控件inputPassword占位符=密码>
                    < / DIV>
                < / DIV>
            < /表及GT;
        < / DIV>
        < D​​IV CLASS =模式躯>
            <按钮NG点击=submitData(用户名,密码)级=BTN BTN-主要数据解雇=莫代尔ARIA隐藏=真>登录< /按钮>
        < / DIV>
    < / DIV>

HTML code调用哪个型号登录

 < D​​IV CLASS =导航栏>
      < D​​IV CLASS =Navbar的内部>
        <一类=BTN数据切换=莫代尔数据目标=#登陆GT&;登录和LT; / A>
      < / DIV>
< / DIV>

AngulurJS code

 <脚本>                    VAR应用= angular.module('对myApp',[]);
                    app.controller('tasksCtrl',函数($范围,$ HTTP){
                        $ scope.submitData =功能(用户名,密码){
                            无功配置= {
                               params:一个{
                                   用户名:用​​户名,密码:密码
                               }
                            };
                        };
                        //$http.get(\"data.json)
                        $ http.get(/ TODO / API / 1.0 /任务)
                        .success(功能(响应){
                            的console.log(response.tasks)
                            $ scope.tasks = response.tasks;
                        });                        $ scope.editTask =功能(任务){
                            $ scope.selectedTask =任务;
                        };
                        $ scope.removeRow =功能(任务){
                            $ scope.tasks.splice(任务,1);
                        };
                        $ scope.addNewTask =功能(){
                            //$scope.tasks.push({ti​​tle:$ scope.task1,说明:$ scope.description1});
                            $ scope.tasks.push({标题:$ scope.task1,说明:$ scope.description1});
                            $ scope.task1 ='';
                            $ scope.description1 ='';
                            // $ scope.tasks.push('dhsh');
                        };
                    });
        < / SCRIPT>

REST的API-SERVER

 导入6
从瓶进口瓶,jsonify,中止,请求,make_response,url_for,render_template
从flask.ext.httpauth进口HTTPBasicAuth应用=瓶(__ name__,static_url_path =)
AUTH = HTTPBasicAuth()
@ auth.get_password
高清get_password(用户名):
    如果用户名==管理员:
        返回'1234'
    返回None
@ auth.error_handler
未经授权的高清():
    返回make_response(jsonify({'错误':'未经授权的访问'}),403)
@ app.errorhandler(400)
高清BAD_REQUEST(错误):
    返回make_response(jsonify({'错误':'坏请求'}),400)
@ app.errorhandler(404)
高清NOT_FOUND(错误):
    返回make_response(jsonify({'错误':'找不到'}),404)
任务= [
    {
        'ID':1,
        标题:u'Buy杂货,
        说明:u'Milk,奶酪,比萨,水果,泰诺,
        完成:假
    },
    {
        'ID':2,
        标题:u'Learn Python的,
        说明:u'Need找到在网络上一个良好的Python教程,
        完成:假
    }
]
高清make_public_task(任务):
    new_task = {}
    在任务栏:
        如果现场=='ID':
            new_task ['URI'] = url_for('get_task',TASK_ID =任务['身份证'],
                                      _external = TRUE)
        其他:
            new_task [现场] =任务[现场]
    返回new_task@ app.route(/)
@ auth.login_required
高清指数():
   返回render_template('的index.html')@ app.route('/ TODO / API / 1.0 /任务,方法= ['GET'])
@ auth.login_required
高清get_tasks():
    返回jsonify({'任务':[在任务任务make_public_task(任务)]})
@ app.route('/ TODO / API / 1.0 /任务/< INT:TASK_ID>',方法= ['GET'])
@ auth.login_required
高清get_task(TASK_ID):
    任务= [在任务任务的任务,如果任务['身份证'] == TASK_ID]
    如果len(任务)== 0:
        中止(404)
    返回jsonify({'任务':make_public_task(任务[0])})
@ app.route('/ TODO / API / 1.0 /任务,方法= ['POST'])
@ auth.login_required
高清create_task():
    如果不是没有request.json request.json或标题:
        中止(400)
    任务= {
        ID:任务[-1] ['身份证'] + 1,
        标题:request.json ['标题'],
        说明:request.json.get(描述,),
        完成:假
    }
    tasks.append(任务)
    返回jsonify({'任务':make_public_task(任务)}),201
@ app.route('/ TODO / API / 1.0 /任务/< INT:TASK_ID>',方法= ['把'])
@ auth.login_required
高清update_task(TASK_ID):
    任务= [在任务任务的任务,如果任务['身份证'] == TASK_ID]
    如果len(任务)== 0:
        中止(404)
    如果没有request.json:
        中止(400)
    如果'标题'在request.json和\\
            不isinstance(request.json ['标题'],six.string_types):
        中止(400)
    如果说明中request.json和\\
            不isinstance(request.json ['说明'],six.string_types):
        中止(400)
    如果request.json和类型(['做'] request.json)'做'不是布尔:
        中止(400)
    任务[0] ['标题'] = request.json.get('标题',任务[0] ['标题'])
    任务[0] ['说明'] = request.json.get(说明,
                                              任务[0] ['说明'])
    任务[0] ['完成'] = request.json.get('做',任务[0] ['做'])
    返回jsonify({'任务':make_public_task(任务[0])})
@ app.route('/ TODO / API / 1.0 /任务/< INT:TASK_ID>',方法= ['删除'])
@ auth.login_required
高清delete_task(TASK_ID):
    任务= [在任务任务的任务,如果任务['身份证'] == TASK_ID]
    如果len(任务)== 0:
        中止(404)
    tasks.remove(任务[0])
    返回jsonify({结果:真正})
如果__name__ =='__main__':
    app.run(调试=真)


解决方案

您从客户端的基本身份验证的方式是通过提供授权:基本< EN codeD的用户名:密码> 在HTTP请求头。

连接codeD的用户名:密码将在下面描述的特定方式完成的:


  

      
  1. 的用户名和密码,合并成一个字符串用户名:密码

  2.   
  3. 结果字符串然后连接codeD使用Base64编码的RFC2045-MIME变种,但不限于76字符/行[9]

  4.   

所以修改REST调用,包括上面的头在你的Angularjs code或找到一个图书馆做。

作为@Boris在评论中提到上面,看到该链接的http://jasonwatmore.com/post/2014/05/26/AngularJS-Basic-HTTP-Authentication-Example.aspx它写入你想要的东西,漂亮的角服务

Guys If My Question is not clear please comment below.

Basic HTTP Authentication for REST API in flask+angularjs

I just want to login to the flask-rest-api in angularjs, I don't know how to send the login info (username and password)to flask-rest-api. In this app There is one table after successfully login and it will load the data. Here we are not using any data-base but username and password is hard-coded in rest-server code. and username="admin" and password="1234". When can modify, update, addNewData. I took this from this blog, here they are using in knockout, I am trying to in Angularjs

Login form

<div id="login" class="modal hide fade" tabindex="=1" role="dialog" aria-labelledby="loginLabel" aria-hidden="true">
        <div class="modal-header">
            <h3 id="loginLabel">Sign In</h3>
        </div>
        <div class="modal-body">
            <form class="form-horizontal">
                <div class="control-group">
                    <label class="control-label" for="inputUsername">Username</label>
                    <div class="controls">
                        <input ng-model="username" type="text" id="inputUsername" placeholder="Username">
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="inputPassword">Password</label>
                    <div class="controls">
                        <input ng-model="password" type="password" id="inputPassword" placeholder="Password">
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button ng-click="submitData(username, password)" class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Sign In</button>
        </div>
    </div>

HTML Code Which call Login Model

<div class="navbar">
      <div class="navbar-inner">
        <a class="btn" data-toggle="modal" data-target="#login">Login</a>
      </div>
</div>

AngulurJS code

<script>

                    var app = angular.module('myApp', []);
                    app.controller('tasksCtrl', function($scope, $http) {
                        $scope.submitData=function(username, password){
                            var config={
                               params:{
                                   username:username, password:password
                               }
                            };
                        };
                        //$http.get("data.json")
                        $http.get("/todo/api/v1.0/tasks")
                        .success(function(response) {
                            console.log(response.tasks)
                            $scope.tasks = response.tasks;
                        });

                        $scope.editTask = function(task) {
                            $scope.selectedTask = task;
                        };
                        $scope.removeRow = function(task) {
                            $scope.tasks.splice(task, 1);
                        };
                        $scope.addNewTask = function() {
                            //$scope.tasks.push({title :$scope.task1,description: $scope.description1});
                            $scope.tasks.push({title: $scope.task1, description: $scope.description1});
                            $scope.task1 = '';
                            $scope.description1 = '';
                            //   $scope.tasks.push('dhsh');
                        };
                    });    
        </script>

REST-API-SERVER

import six
from flask import Flask, jsonify, abort, request, make_response, url_for, render_template 
from flask.ext.httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path="")
auth = HTTPBasicAuth()


@auth.get_password
def get_password(username):
    if username == 'admin':
        return '1234'
    return None


@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403)


@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]


def make_public_task(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id=task['id'],
                                      _external=True)
        else:
            new_task[field] = task[field]
    return new_task

@app.route('/')
@auth.login_required
def index():
   return render_template('index.html')

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': [make_public_task(task) for task in tasks]})


@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
@auth.login_required
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task': make_public_task(task[0])})


@app.route('/todo/api/v1.0/tasks', methods=['POST'])
@auth.login_required
def create_task():
    if not request.json or 'title' not in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': make_public_task(task)}), 201


@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
@auth.login_required
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and \
            not isinstance(request.json['title'], six.string_types):
        abort(400)
    if 'description' in request.json and \
            not isinstance(request.json['description'], six.string_types):
        abort(400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        abort(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description',
                                              task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': make_public_task(task[0])})


@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
@auth.login_required
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True})


if __name__ == '__main__':
    app.run(debug=True)

解决方案

The way you make basic authentication from client side is by supplying Authorization: Basic <encoded username:password> header in HTTP request.

encoded username:password is done in specific manner described below:

  1. Username and password are combined into a string "username:password"
  2. The resulting string is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line[9]

So modify your rest calls to include above header in your Angularjs code or find a library to do that.

as @Boris mentioned in comments above, see this link http://jasonwatmore.com/post/2014/05/26/AngularJS-Basic-HTTP-Authentication-Example.aspx it has nice Angular service written to do just what you want

这篇关于如何让用户使用HTTP认证登录保护的烧瓶REST的API在Angularjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆