【问题标题】:401 Client Error: Unauthorized url. Flask python401 客户端错误:未经授权的 URL。烧瓶蟒蛇
【发布时间】:2021-05-29 07:11:57
【问题描述】:

我有一个使用 API 进行身份验证的程序,当登录时通过此 API 上的联系人中的 ID 进行搜索。 登录工作正常,但是当我尝试查找联系人时,会发生此错误: 401 客户端错误:未经授权的 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',
    }
)

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

【问题讨论】:

  • 这里有什么想法吗?

标签: python flask authlib flask-oauthlib


【解决方案1】:

错误表明您没有包含您的授权标头。根据此处使用的基本身份验证标准 (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)

【讨论】:

  • 感谢您的回复。当我使用 access_token 但使用 base64 平台 ID、平台密码时不起作用
  • 可以同时使用 Authorization Basic 和 Bearer 吗?
  • 我不这么认为,它们是两个不同的标准,用于不同的流程。据我了解,承载认证方案更适合 oauth2。为了使用 Bearer 身份验证,您需要更改 client_kwargs 中的 token_endpoint_auth_method。
猜你喜欢
  • 2018-07-07
  • 2022-11-11
  • 1970-01-01
  • 2023-03-30
  • 2021-01-07
  • 2022-10-25
  • 1970-01-01
  • 2021-10-26
  • 2013-08-03
相关资源
最近更新 更多