Mike D Hovhannisyan
Mike D Hovhannisyan

Reputation: 434

JWT generated token is invalid

Here is the Flask app

import jwt

from datetime import datetime, timedelta
from flask import Flask, request, jsonify, make_response
from flask_socketio import SocketIO, send
from flask_sqlalchemy import SQLAlchemy

from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps


app = Flask(__name__)
app.config['SECRET_KEY'] = 'myrandomsecretkey'
print(app.config['SECRET_KEY'])
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)


def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None

        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        if not token:
            return jsonify({'message': 'Token is missing!'}), 401

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'])
            current_user = User.query.filter_by(public_id=data['public_id']).first()
        except:
            return jsonify({'message': 'Token is invalid!'}), 401

        return f(current_user, *args, **kwargs)

    return decorated


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    first_name = db.Column(db.String(30))
    last_name = db.Column(db.String(40))
    first_name = db.Column(db.String(30), nullable=False)
    date_joined = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    password = db.Column(db.String(80))

    def __repr__(self):
        return f"User('{self.first_name}', '{self.last_name}')"


@app.route('/user_registration', methods=['POST'])
def create_user():
    data = request.get_json()
    hashed_password = generate_password_hash(data['password'], method='sha256')
    new_user = User(first_name=data['first_name'],
                    last_name=data['last_name'], password=hashed_password, username=data['username'])
    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': 'new_user_created'})


@app.route('/login', methods=['POST'])
def login():
    auth = request.authorization

    if not auth.password:
        return make_response('Authentication credentials were not provided', 418)

    user = User.query.filter_by(username=auth.username).first()
    if not user:
        return jsonify({'message': 'No user found'})

    if check_password_hash(user.password, auth.password):
        token = jwt.encode({'username': user.username, 'exp': datetime.utcnow() +
                           timedelta(minutes=30)}, app.config['SECRET_KEY'])
        print(token)
        return jsonify({'token': token})

    return jsonify({'message': 'No user found'})


@app.route('/user', methods=['GET'])
@token_required
def get_all_users(current_user):
    print(current_user)

    if not current_user.admin:
        return jsonify({'message': 'Cannot perform that function!'})

    users = User.query.all()

    output = []

    for user in users:
        user_data = {}
        user_data['username'] = user.username
        user_data['first_name'] = user.first_name
        user_data['last_name'] = user.last_name
        output.append(user_data)

    return jsonify({'users': output})

After logging in I get the token and when I use in request in Postamn I put it in headers, the key is x-access-token and put the generated token as value but every this I get this error message

"message": "Token is invalid!"

I copied the the authorization part from a tutorial and they were decoding the token before returning it like this

return jsonify({'token' : token.decode('UTF-8')})

when I decode it it returns error saying that I can't decode a string.

This is the tutorial from which I got most parts https://www.youtube.com/watch?v=WxGBoY5iNXY

So what's the poblem here?

Upvotes: 0

Views: 330

Answers (0)

Related Questions