{“ message”:“ mismatching_state:CSRF警告!请求和响应中的状态不相等”跟随auth0快速入门python 01登录-OAUTH

我用我的Flask应用程序实现了auth0 quickstart python 01-login,并且正在收到以下响应:

{“ message”:“ mismatching_state:CSRF警告!请求和响应中的状态不相等。 }

以下是该代码逻辑的摘要

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"/api/*": {"origins": "*"}})
    

    '''
    @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('>>>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("auth.callback",_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))

请注意,对于我的.env文件我有

  • AUTH0_CLIENT_ID ='l6yng5LFtKZIFZ6I56XXXXXXXX'
  • AUTH0_DOMAIN ='double-helixx.us.auth0.com'
  • AUTH0_CLIENT_SECRET ='egP3YRyAqtnHjtIkmnzWMPC0btJ3oN-odV001t9pgbKvc6nlT96PPrYsveJzxTce'
  • AUTH0_CALLBACK_URL ='http://127.0.0.1:5000 / callback'
  • AUTH0_AUDIENCE ='MYIMAGE'

也许这是我这边出错的原因?

  1. Python Samples Failing Out of the Box
  2. authlib/issues
  3. authlib-client-error-state-not-equal-in-request-and-response

对于某些人来说,这似乎是一个新问题,如下所示:

  1. https://github.com/auth0-samples/auth0-python-web-app/issues/58

我的auth0网址为:

auth0 urls

我也已经实现了一个auth.py文件-这可能是导致错误的原因吗?

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():
    """Obtains the Access Token from the Authorization Header
    """
    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 "Bearer".'
        },401)

    elif len(parts) == 1:
        raise AuthError({
            'code': 'invalid_header','description': 'Token not found.'
        },401)

    elif len(parts) > 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

有什么想法吗?

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...