0

I am using token based authentication to restrict the access to user for my site, I am getting following error

{"_status": "ERR", "_error": {"message": "Please provide proper credentials", "code": 401}}weber@weber-desktop:/var/www/lunar-cloud-web-ui/kukunako$ 

my sample code shown below.

class TokenAuth(TokenAuth):
def check_auth(self, token, allowed_roles, resource, method):
    accounts = app.data.driver.db['people']
    return accounts.find_one({'token': token})

app = Eve(__name__,static_url_path='/static', auth = TokenAuth)
app.debug = True,

app.config.update(
   DEBUG=True,
      #EMAIL SETTINGS
      MAIL_SERVER='smtp.gmail.com',
      MAIL_PORT=465,
      MAIL_USE_SSL=True,
      MAIL_USERNAME = '<username>',
      MAIL_PASSWORD = '<password>'
)

 mail=Mail(app)
 socketio = SocketIO(app)


 def create_token(user):
  payload = {
      'sub': str(user['_id']),
      'iat': datetime.now(),
      'exp': datetime.now() + timedelta(days=14)
  }

token = jwt.encode(payload, TOKEN_SECRET)
return token.decode('unicode_escape')

def login_required(f):
   @wraps(f)
   def decorated_function(*args, **kwargs):
    if not request.headers.get('Authorization'):
        response = jsonify(error='Missing authorization header')
        response.status_code = 401
        return response

    payload = parse_token(request)

    if datetime.fromtimestamp(payload['exp']) < datetime.now():
        response = jsonify(error='Token has expired')
        response.status_code = 401
        return response

    g.user_id = payload['sub']

    return f(*args, **kwargs)

return decorated_function

 @app.route('/auth/login', methods=['POST'])
    def login():
        accounts = app.data.driver.db['people']
        user = accounts.find_one({'email': request.json['email']})
        if not user:
           response = jsonify(error='Your email does not exist')
           response.status_code = 401
           return response
        if not user['email_confirmed'] == True:
           response = jsonify(error='Email is not confirmed')
           response.status_code = 401
           return response
        if not user or not check_password_hash(user['password']['password'],      request.json['password']):
           response = jsonify(error='Wrong Email or Password')
           response.status_code = 401
           return response
         token = create_token(user)

        return jsonify(token=token)

my all code is show in following for settings file and server code file settings file

server code file

1 Answer 1

1

How are you testing it?

I can think of two possible problems.

  1. JWT token needs to be base64 encoded
  2. You may have forgotten : at the end

e.g. If your token is as follows (Taken from jwt.io site)

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

You need to do the following:

$ echo 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ:' | base64
ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SnpkV0lpT2lJeE1qTTBOVFkzT0Rrd0lpd2libUZ0WlNJNklrcHZhRzRnUkc5bElpd2lZV1J0YVc0aU9uUnlkV1Y5LlRKVkE5NU9yTTdFMmNCYWIzMFJNSHJIRGNFZnhqb1laZ2VGT05GaDdIZ1E6Cg==

Now use this as follows (with curl)

curl -H "Authorization Basic ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SnpkV0lpT2lJeE1qTTBOVFkzT0Rrd0lpd2libUZ0WlNJNklrcHZhRzRnUkc5bElpd2lZV1J0YVc0aU9uUnlkV1Y5LlRKVkE5NU9yTTdFMmNCYWIzMFJNSHJIRGNFZnhqb1laZ2VGT05GaDdIZ1E6Cg==" http://127.0.0.1:5000/my_secure_endpoint
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.