title: { "message": "mismatching_state: CSRF Warning! State not equal in request and response." } following auth0 quickstart python 01-login - OAUTH
body: <p>I implemented auth0 <a href="https://auth0.com/docs/quickstart/webapp/python/01-login" rel="nofollow noreferrer">quickstart python 01-login</a> with my Flask Application and am receiving this response:</p>
  <blockquote>
  <p>{ &quot;message&quot;: &quot;mismatching_state: CSRF Warning! State not equal in request and response.&quot; }</p>
  </blockquote>
  <p>Here is a snippet of that code logic:</p>
  <pre><code>from models import setup_db, Bay, db_drop_and_create_all
  from flask_sqlalchemy import SQLAlchemy
  from flask_cors import CORS
  from jinja2 import Environment, PackageLoader
  from flask import Flask, render_template, request, Response, flash, redirect, url_for, jsonify, abort,session
  from sqlalchemy import Column, String, Integer, create_engine,and_
  from auth import AuthError, requires_auth
  from functools import wraps
  from os import environ as env
  from werkzeug.exceptions import HTTPException
  from dotenv import load_dotenv, find_dotenv
  from authlib.integrations.flask_client import OAuth
  from six.moves.urllib.parse import urlencode
  import json
  import constants
  
  
  
  
  ENV_FILE = find_dotenv()
  if ENV_FILE:
      load_dotenv(ENV_FILE)
  
  AUTH0_CALLBACK_URL = env.get(constants.AUTH0_CALLBACK_URL)
  AUTH0_CLIENT_ID = env.get(constants.AUTH0_CLIENT_ID)
  AUTH0_CLIENT_SECRET = env.get(constants.AUTH0_CLIENT_SECRET)
  AUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN)
  AUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN
  AUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE)
  
  
  def create_app(test_config=None):
      # create and configure the app
      app = Flask(__name__)
    
      oauth = OAuth(app)
      auth0 = oauth.register(
          'auth0',
          client_id=AUTH0_CLIENT_ID,
          client_secret=AUTH0_CLIENT_SECRET,
          api_base_url=AUTH0_BASE_URL,
          access_token_url=AUTH0_BASE_URL + '/oauth/token',
          authorize_url=AUTH0_BASE_URL + '/authorize',
          client_kwargs={
              'scope': 'openid profile email',
          },
      )  
      
      app.secret_key = constants.SECRET_KEY
      app.debug = True
      configedDB = setup_db(app)
      if not configedDB:
        abort(500)
    
      @app.errorhandler(Exception)
      def handle_auth_error(ex):
          response = jsonify(message=str(ex))
          response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
          return response
      
      
  
      '''
      @TODO: Set up CORS. Allow '*' for origins. Delete the sample route after completing the TODOs
      '''
      CORS(app, resources={r&quot;/api/*&quot;: {&quot;origins&quot;: &quot;*&quot;}})
      
  
      '''
      @TODO: Use the after_request decorator to set Access-Control-Allow
      '''
      @app.after_request
      def after_request(response):
          response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')
          response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
          return response
  
      #----------------------------------------------------------------------------#
      # Controllers.
      #----------------------------------------------------------------------------#
  
  
      @app.route('/')
      def index():
          return render_template('index.html')
      
      @app.route('/callback')
      def callback_handling():
          #auth0 = app.config['auth0']
          token = auth0.authorize_access_token()
          resp = auth0.get('userinfo')
          userinfo = resp.json()
          print('&gt;&gt;&gt;USER_INFO',userinfo)
          session[constants.JWT_PAYLOAD] = userinfo
          session[constants.PROFILE_KEY] = {
              'user_id': userinfo['sub'],
              'name': userinfo['name'],
              'picture': userinfo['picture']
          }
          return redirect('/manager/bay/all')
  
      @app.route('/login')
      def login():
          #auth0 = app.config['auth0']
          #state = uuid.uuid4().hex
          #redirect_url = url_for(&quot;auth.callback&quot;, _external=True)
          #auth0.save_authorize_state(redirect_uri=redirect_url, state=state)
          return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE) #, state=state
  
  
      @app.route('/logout')
      def logout():
          session.clear()
          params = {'returnTo': url_for('home', _external=True), 'client_id': AUTH0_CLIENT_ID}
          return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))
  </code></pre>
  <p>Please note that for my .env file I have:</p>
  <ul>
  <li>AUTH0_CLIENT_ID='l6yng5LFtKZIFZ6I56XXXXXXXX'</li>
  <li>AUTH0_DOMAIN='double-helixx.us.auth0.com'</li>
  <li>AUTH0_CLIENT_SECRET='egP3YRyAqtnHjtIkmnzWMPC0btJ3oN-odV001t9pgbKvc6nlT96PPrYsVeJzxTce'</li>
  <li>AUTH0_CALLBACK_URL='http://127.0.0.1:5000/callback'</li>
  <li>AUTH0_AUDIENCE='MYIMAGE'</li>
  </ul>
  <p>Maybe this is the cause of the error from my side?</p>
  <ol>
  <li><a href="https://github.com/auth0-samples/auth0-python-web-app/issues/43" rel="nofollow noreferrer">Python Samples Failing Out of the Box</a></li>
  <li><a href="https://github.com/lepture/authlib/issues/81" rel="nofollow noreferrer">authlib/issues</a></li>
  <li><a href="https://stackoverflow.com/questions/50941758/authlib-client-error-state-not-equal-in-request-and-response">authlib-client-error-state-not-equal-in-request-and-response</a></li>
  </ol>
  <p>It seems this is a recent issue for some people as well shown in here:</p>
  <ol start="4">
  <li><a href="https://github.com/auth0-samples/auth0-python-web-app/issues/58" rel="nofollow noreferrer">https://github.com/auth0-samples/auth0-python-web-app/issues/58</a></li>
  </ol>
  <p>My auth0 Urls are:<br />
  <a href="https://i.stack.imgur.com/mXrQ8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mXrQ8.png" alt="auth0 urls" /></a></p>
  <p>I have an auth.py file as well that I have implemented- that may be the cause of the error?</p>
  <pre><code>import json
  from flask import request, _request_ctx_stack
  from functools import wraps
  from jose import jwt
  from urllib.request import urlopen
  
  
  AUTH0_DOMAIN = 'double-helixx.us.auth0.com'
  ALGORITHMS = ['RS256']
  API_AUDIENCE = 'image'
  
  ## AuthError Exception
  '''
  AuthError Exception
  A standardized way to communicate auth failure modes.
  '''
  class AuthError(Exception):
      def __init__(self, error, status_code):
          self.error = error
          self.status_code = status_code
  
  
  ## Auth Header
  
  '''
  @ implement get_token_auth_header() method
      it should attempt to get the header from the request
          it should raise an AuthError if no header is present
      it should attempt to split bearer and the token
          it should raise an AuthError if the header is malformed
      return the token part of the header
  '''
  def get_token_auth_header():
      &quot;&quot;&quot;Obtains the Access Token from the Authorization Header
      &quot;&quot;&quot;
      auth = request.headers.get('Authorization', None)
      if not auth:
          raise AuthError({
              'code': 'authorization_header_missing',
              'description': 'Authorization header is expected.'
          }, 401)
  
      parts = auth.split()
      if parts[0].lower() != 'bearer':
          raise AuthError({
              'code': 'invalid_header',
              'description': 'Authorization header must start with &quot;Bearer&quot;.'
          }, 401)
  
      elif len(parts) == 1:
          raise AuthError({
              'code': 'invalid_header',
              'description': 'Token not found.'
          }, 401)
  
      elif len(parts) &gt; 2:
          raise AuthError({
              'code': 'invalid_header',
              'description': 'Authorization header must be bearer token.'
          }, 401)
  
      token = parts[1]
      return token
  
  '''
  @ implement check_permissions(permission, payload) method
      @INPUTS
          permission: string permission (i.e. 'post:drink')
          payload: decoded jwt payload
  
      it should raise an AuthError if permissions are not included in the payload
          !!NOTE check your RBAC settings in Auth0
      it should raise an AuthError if the requested permission string is not in the payload permissions array
      return true otherwise
  '''
  def check_permissions(permission, payload):
      if 'permissions' not in payload:
                          raise AuthError({
                              'code': 'invalid_claims',
                              'description': 'Permissions not included in JWT.'
                          }, 400)
  
      if permission not in payload['permissions']:
          raise AuthError({
              'code': 'unauthorized',
              'description': 'Permission not found.'
          }, 403)
      return True
              
  
  '''
  @ implement verify_decode_jwt(token) method
      @INPUTS
          token: a json web token (string)
  
      it should be an Auth0 token with key id (kid)
      it should verify the token using Auth0 /.well-known/jwks.json
      it should decode the payload from the token
      it should validate the claims
      return the decoded payload
  
      !!NOTE urlopen has a common certificate error described here: https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org
  '''
  def verify_decode_jwt(token):
      jsonurl = urlopen(f'https://{AUTH0_DOMAIN}/.well-known/jwks.json')
      jwks = json.loads(jsonurl.read())
      unverified_header = jwt.get_unverified_header(token)
      rsa_key = {}
      if 'kid' not in unverified_header:
          raise AuthError({
              'code': 'invalid_header',
              'description': 'Authorization malformed.'
          }, 401)
  
      for key in jwks['keys']:
          if key['kid'] == unverified_header['kid']:
              rsa_key = {
                  'kty': key['kty'],
                  'kid': key['kid'],
                  'use': key['use'],
                  'n': key['n'],
                  'e': key['e']
              }
      if rsa_key:
          try:
              payload = jwt.decode(
                  token,
                  rsa_key,
                  algorithms=ALGORITHMS,
                  audience=API_AUDIENCE,
                  issuer='https://' + AUTH0_DOMAIN + '/'
              )
  
              return payload
  
          except jwt.ExpiredSignatureError:
              raise AuthError({
                  'code': 'token_expired',
                  'description': 'Token expired.'
              }, 401)
  
          except jwt.JWTClaimsError:
              raise AuthError({
                  'code': 'invalid_claims',
                  'description': 'Incorrect claims. Please, check the audience and issuer.'
              }, 401)
          except Exception:
              raise AuthError({
                  'code': 'invalid_header',
                  'description': 'Unable to parse authentication token.'
              }, 400)
      raise AuthError({
                  'code': 'invalid_header',
                  'description': 'Unable to find the appropriate key.'
              }, 400)
  
  
  '''
  @TODO implement @requires_auth(permission) decorator method
      @INPUTS
          permission: string permission (i.e. 'post:drink')
  
      it should use the get_token_auth_header method to get the token
      it should use the verify_decode_jwt method to decode the jwt
      it should use the check_permissions method validate claims and check the requested permission
      return the decorator which passes the decoded payload to the decorated method
  '''
  def requires_auth(permission=''):
      def requires_auth_decorator(f):
          @wraps(f)
          def wrapper(*args, **kwargs):
              token = get_token_auth_header()
              payload = verify_decode_jwt(token)
              check_permissions(permission, payload)
              return f(payload, *args, **kwargs)
  
          return wrapper
      return requires_auth_decorator
  </code></pre>
  <p>Any ideas?</p>