如何在Flask REST API服务中使用Keycloak

时间:2018-06-17 10:37:09

标签: flask keycloak flask-restful

我正在尝试将Keycloak实施到我的Flask Rest服务,但它总是给出以下错误。

{“error”:“invalid_token”,“error_description”:“令牌必需但无效”}

的client_secrets.json

<html>

run.py

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != \/* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

# Set the python io encoding to UTF-8 by default if not set.
if [ -z ${PYTHONIOENCODING+x} ]; then export PYTHONIOENCODING=utf8; fi

export PYTHONPATH="${DIR}:${PYTHONPATH}"

python -m mssqlcli.main "$@"

enter image description here

如果有任何问题,任何人都有自己的想法。

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并且我(最终是\ o /)使它正常工作。请尝试以下操作:

'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post'
'OIDC_TOKEN_TYPE_HINT': 'access_token'

还删除所需作用域的列表,以避免出现任何可能的错误:

@oidc.accept_token(require_token=True)

答案 1 :(得分:0)

如果您尝试访问Rest服务,例如:

http://127.0.0.1:5001/api

然后它将不起作用,因为没有访问令牌。

相反,您可以做的是访问http://127.0.0.1:5001/private并从内部通过标题中的令牌调用/ api来调用

  @app.route('/private')
  @oidc.require_login
  def hello_me():
    info = oidc.user_getinfo(['email', 'openid_id'])

    if user_id in oidc.credentials_store:

        try:
            from oauth2client.client import OAuth2Credentials
            access_token = OAuth2Credentials.from_json(oidc.credentials_store[user_id]).access_token

            headers = {'Authorization': f'Bearer {access_token}'}

            access_like_this = requests.get('http://localhost:5001/api', headers=headers).text
        except:

            access_like_this = "we failed"

        return f'Hello, api: {access_like_this} <a href="/">Return</a>'

    else:

        return f'Ops, <a href="/">Return</a>'