0

我有一个使用 API 进行身份验证的程序,并在登录时通过此 API 上的联系人中的 ID 进行搜索。登录工作正常,但是当我尝试查找联系人时,会发生此错误:401 Client Error: Unauthorized for url: https://api.moxiworks.com/api/contacts/12345678 在 Postman 上尝试时也会出现同样的问题,如下所示图片: 邮递员截图显示错误 登录后我重定向到主路由,代码如下:

@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',
    }
)

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

4

1 回答 1

0

该错误表明您没有包含您的授权标头。根据此处使用的基本身份验证标准 ( RFC 7617 ),您应该在 Authorization 标头中包含访问令牌而不是参数。因此,它应该看起来像这样在此处输入图像描述

或者在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)
于 2021-05-29T15:47:07.637 回答