I was trying to create a flask app with user-login API call that generates access and refresh token and upon successful creation redirect back to homepage view which has jwt_required(optional=True) decorator but no matter how i try to save the token i'm unable to fetch it via get_jwt()
This is the API for generating the access and refresh token.
class UserLogin(MethodResource, Resource):
@doc(description='This is User Login Endpoint', tags=['User Endpoint'])
@use_kwargs(User_RequestSchema(exclude=("name", "email","admin")))
@marshal_with(Login_ResponseToken, code=200, description="Success | Returns: \nUser Registered Succesfully")
@marshal_with(Msg_ResponseSchema, code=401, description="Unauthorized | Returns: \n-Invalid User Credentials!")
@marshal_with(Msg_ResponseSchema, code=400, description="Bad Request | Returns: \n-Error loading Json body on request")
def post(self,**kwargs):
"""
If user roll_num and password correct create a new access and refresh token
else return invalid credentials 401 error
"""
try:
schema = User_RequestSchema(exclude=("name", "email","admin"))
data = schema.load(kwargs,unknown=EXCLUDE)
except:
output = {"message":"Error loading Json body in request"}
return output, 400 #Status-Bad Request
user = UserModel.find_by_rollnum(data['roll_num'])
# User Present and password correct
if user is not None and user.check_password(data['password']) and user.roll_num==data['roll_num']:
additional_claims = {"admin_access":user.admin}
access_token = create_access_token(identity=user.roll_num, additional_claims=additional_claims,fresh=True)
refresh_token = create_refresh_token(user.roll_num)
resp = jsonify(login=True)
set_access_cookies(resp, access_token.encode('utf-8'))
set_refresh_cookies(resp, refresh_token.encode('utf-8'))
resp.set_cookie('X-CSRF-TOKEN-ACCESS', access_token.encode('utf-8'))
resp.set_cookie('X-CSRF-TOKEN-REFRESH', refresh_token.encode('utf-8'))
output={"access_token":access_token,
"refresh_token":refresh_token,
"message": "Successful Login"}
return output, 200 # Status-OK
output = {"message": "Invalid User Credentials!"}
return output, 401 # Status-Unauthorized
This is the code that calls the login API and provides login information from login Form
@auth.route("/user_login", methods=["GET", "POST"])
def user_login():
form = LoginForm()
if form.validate_on_submit():
data = {"roll_num": form.roll_num.data,
"password": form.password.data}
# send request to login API
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Bearer {token}"
r = requests.post('http://localhost:5000/login', json=data, headers=headers)
if r.status_code==401:
flash("Wrong Roll Number or Password")
elif r.status_code==200:
print("Login correct")
flash("Log In successful")
access_token = r.json()['access_token']
resp = redirect(url_for('home.index'),access_token)
resp.headers = {'Authorization': 'Bearer {}'.format(access_token)}
return resp
print('Login_response',r)
print('Status Code',r.status_code)
print('data',r.text)
return render_template("login.html", form=form)
This is where the login should redirect on successful token generation
@home.route('/')
@home.route('/index')
@jwt_required(optional=True, locations=['headers', 'cookies'])
def index():
logged_in = 0
admin = 0
head = get_jwt_header()
print(head)
identity = get_jwt_identity()
print(identity)
claims = get_jwt()
print('claims:', claims)
if len(claims)!=0:
logged_in = 1
# If user is admin give ability to register
if claims['admin_access']==1:
admin = 1
print("Logged In: ", logged_in)
print("Admin: ", admin)
return render_template('index.html', admin=admin, logged_in=logged_in)
As far as I read should be able to get jwt claims and identity form the stored token, but no matter what I do i can't get this to work. It works in post man through assignment in environment variable. I can't figure out what I'm doing wrong?