401 客户端错误:未经授权的 URL。烧瓶蟒蛇

时间:2021-05-29 07:11:57

标签: python flask authlib flask-oauthlib

我有一个程序可以使用 API 进行身份验证,并且在登录时通过此 API 上的联系人中的 ID 进行搜索。 登录工作正常,但是当我尝试查找联系人时发生此错误: 401 客户端错误:网址未经授权:https://api.moxiworks.com/api/contacts/12345678 在 Postman 上尝试时会发生同样的问题,如下图所示: Postman screenshot to display error 登录后,我重定向到家庭路线,这是代码:

@app.route('/home', methods=["GET", "POST"])
@login_required
def home():

    if request.method == "POST":
        found = request.form.get('id')

        #base64 encoded Partner ID and Partner Secret
        sample_string = ('%s:%s' % (os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"))).replace('\n', '')
        sample_string_bytes = sample_string.encode("ascii")
        base64_bytes = base64.b64encode(sample_string_bytes)
        base64_string = base64_bytes.decode("ascii")

        if not found:
            return render_template('apology', err='must provide id')

        try:
            token = session['token']
            response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
                                    token=token,
                                    headers={
                                        'Content-Type': 'application/x-www-form-urlencoded',
                                        'Authorization': 'Basic %s' % base64_string,
                                        'Accept': 'application/vnd.moxi-platform+json;version=1',
                                        'Cookie': '_wms_svc_public_session'
                                    })
            if response.status_code == 429:
                flash('too many requests, wait for 60 seconds then will get your results')
                time.sleep(60)
                response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
                                    token=token,
                                    headers={
                                        'Content-Type': 'application/x-www-form-urlencoded',
                                        'Authorization': 'Basic %s' % base64_string,
                                        'Accept': 'application/vnd.moxi-platform+json;version=1',
                                        'Cookie': '_wms_svc_public_session'
                                    })


            # If the response was successful, no Exception will be raised
            response.raise_for_status()
        except HTTPError as err:
            return render_template('apology.html', err=err)
        except Exception as err:
            return render_template('apology.html', err=err)
        else:
            try:
                contact = response.json()

                return render_template('data.html',
                                       contact1=contact['agent_uuid'], contact2=contact['moxi_works_agent_id'],
                                       contact3=contact['partner_contact_id'], contact4=contact['contact_name'],
                                       contact5=contact['primary_email_address'], contact6=contact['secondary_email_address'],
                                       contact7=contact['primary_phone_number'], contact8=contact['secondary_phone_number'])
            except (KeyError, TypeError, ValueError) as err:
                return render_template('apology.html', err=err)

    else:
        return render_template('home.html')

我想念什么?或者我的代码有什么问题?

这里是认证寄存器:

moxi = oauth.register(
    name='moxi',
    client_id=os.getenv("CLIENT_ID"),
    client_secret=os.getenv("CLIENT_SECRET"),
    access_token_url='https://sso.moxiworks.com/oauth/token',
    access_token_params={'grant_type': 'authorization_code'},
    authorize_url='https://sso.moxiworks.com/oauth/authorize',
    authorize_params={'response_type': 'code'},
    api_base_url='https://api.moxiworks.com/api/contacts/',
    userinfo_endpoint='https://sso.moxiworks.com/agent/profile',  # This is only needed if using openId to fetch user info
    client_kwargs = {
    'scope': 'profile',
    'token_endpoint_auth_method': 'client_secret_basic',
    'token_placement': 'header',
    }
)

请帮我弄清楚如何解决这个问题? 提前致谢。

1 个答案:

答案 0 :(得分:0)

错误表明您没有包含授权标头。根据此处使用的基本身份验证标准 (RFC 7617),您应该在 Authorization 标头中包含访问令牌而不是参数。因此,它应该类似于 enter image description here

或者在python代码上,它看起来像这样

import requests

url = "https://example.com/api/contacts/1234"

payload = {}
headers = {'Authorization': 'Basic <access_token>'}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)