angularjspython-2.7flaskflask-sqlalchemyflask-jwt

Flask jwt auth endpoint returns 400


I am currently creating a small application and have run into a problem. I am using the flask jwt module in order for the user to retrieve a token to be able to access the api's exposed in python. I am using angularjs for my frontend development. When I try to login the server that my api's reside on return a 400 error

"POST /auth HTTP/1.1" 400 

according to the documentation, all I have to do is pass my credentials to the auth endpoint and I should be able to get back a token as demonstrated on the page: https://pythonhosted.org/Flask-JWT/

Here is my current app server implementation:

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from flask.ext.cors import CORS
from werkzeug.security import safe_str_cmp
from wol import User, db
import hashlib


def authenticate(username, password):
    user = User.query.filter_by(username=username).first()
    print str(user)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user


def identity(payload):
    user_id = payload['identity']
    return User.query.filter_by(UserID=user_id)


app = Flask(__name__)
CORS(app)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)
admin = User("test", "test1")
db.session.add(admin)
db.session.commit()

@app.route('/protected')
@jwt_required()
def protected():
    return '%s' % current_identity


@app.route('/register', methods=['POST'])
def register(username, password, confirmPassword):
    # we probably want to hash these passwords when storing in db
    # we'll hash both the password and confirm password
    pass_hash = hashlib.sha256(password).hexdigest()
    conf_pass_hash = hashlib.sha256(confirmPassword).hexdigest()

    if pass_hash == conf_pass_hash:
        new_user = User(username, password)
        db.session.add(new_user)
        db.session.commit()

@app.route('/allusers')
def get_all_users():
    users = User.query.all()
    return users


if __name__ == '__main__':
    app.run(host='0.0.0.0')

and here is my angularjs implementation:

(function() {
      angular.module('loginApp', []).controller('loginController', function($scope, $http) {
        $scope.data = {};

        //we can now process the form
        $scope.processForm = function() {
          $http({
          method  : 'POST',
          url     : 'http://192.168.0.99:5000/auth',
          data    : $.param($scope.data),  // pass in data as strings
          headers : { 'Content-Type': 'application/json' }  // set the headers so angular passing info as form data (not request payload)
         })
          .success(function(data) {
            console.log("successful")
            console.log(data);
          });
        };
      });
  }());

I have set debug mode on the server which runs my python code and it returns a 400


Solution

  • Oh, this is because you're using $.param, which serializes objects into query string parameters, but the API expects JSON. You should do:

    data: JSON.stringify($scope.data)
    

    instead.