Flask 和 React - Spotify 授权后处理令牌

2024-02-10

我已经在我的应用程序中实现了 JWT 用于用户登录(在 Spotify Auth 之前),如下所示:

Flask

@auth_blueprint.route('/auth/login', methods=['POST'])
def login_user():
    # get post data
    post_data = request.get_json()
    response_object = {
        'status': 'fail',
        'message': 'Invalid payload.'
    }
    if not post_data:
        return jsonify(response_object), 400
    email = post_data.get('email')
    password = post_data.get('password')
    try:
        # fetch the user data
        user = User.query.filter_by(email=email).first()
        if user and bcrypt.check_password_hash(user.password, password):
            auth_token = user.encode_auth_token(user.id)
            if auth_token:
                response_object['status'] = 'success'
                response_object['message'] = 'Successfully logged in.'
                response_object['auth_token'] = auth_token.decode()
                return jsonify(response_object), 200
        else:
            response_object['message'] = 'User does not exist.'
            return jsonify(response_object), 404
    except Exception:
        response_object['message'] = 'Try again.'
        return jsonify(response_object), 500

这些是我的 SQLAlchemy 的方法User(db.Model)

def encode_auth_token(self, user_id):
        """Generates the auth token"""
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(
                    days=current_app.config.get('TOKEN_EXPIRATION_DAYS'), 
                    seconds=current_app.config.get('TOKEN_EXPIRATION_SECONDS')
                ),
                'iat': datetime.datetime.utcnow(),
                'sub': user_id
            }
            return jwt.encode(
                payload,
                current_app.config.get('SECRET_KEY'),
                algorithm='HS256'
            )
        except Exception as e:
            return e

@staticmethod
def decode_auth_token(auth_token):
        """
        Decodes the auth token - :param auth_token: - :return: integer|string
        """
        try:
            payload = jwt.decode(
                auth_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'

React

App.jsx

  loginUser(token) {
    window.localStorage.setItem('authToken', token);
    this.setState({ isAuthenticated: true });
    this.getUsers();
    this.createMessage('Welcome', 'success');
  };

(...)

<Route exact path='/login' render={() => (
  <Form
    isAuthenticated={this.state.isAuthenticated}
    loginUser={this.loginUser}
  />
)} />

and

Form.jsx

handleUserFormSubmit(event) {
    event.preventDefault();
    const data = {
      email: this.state.formData.email,
      password: this.state.formData.password
    };
    const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/auth/${formType.toLowerCase()}`;
    axios.post(url, data)
      .then((res) => {
        this.props.loginUser(res.data.auth_token);
    })

第三方授权+二次App认证

现在我想在 Spotify 回调之后添加第二层身份验证和处理令牌,如下所示:

@spotify_auth_bp.route("/callback", methods=['GET', 'POST'])
def spotify_callback():

    # Auth Step 4: Requests refresh and access tokens
    SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"

    CLIENT_ID =   os.environ.get('SPOTIPY_CLIENT_ID')
    CLIENT_SECRET = os.environ.get('SPOTIPY_CLIENT_SECRET')
    REDIRECT_URI = os.environ.get('SPOTIPY_REDIRECT_URI')

    auth_token = request.args['code']

    code_payload = {
        "grant_type": "authorization_code",
        "code": auth_token,
        "redirect_uri": REDIRECT_URI,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
    }

    post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload)

    # Auth Step 5: Tokens are Returned to Application
    response_data = json.loads(post_request.text)

    access_token = response_data["access_token"]
    refresh_token = response_data["refresh_token"]
    token_type = response_data["token_type"]
    expires_in = response_data["expires_in"]

    # At this point, there is to generate a custom token for the frontend
    # Either a self-contained signed JWT or a random token?
    # In case the token is not a JWT, it should be stored in the session (in case of a stateful API)
    # or in the database (in case of a stateless API)
    # In case of a JWT, the authenticity can be tested by the backend with the signature so it doesn't need to be stored at all?

    res = make_response(redirect('http://localhost/about', code=302))

    return res

Note:这是获取新 Spotify 代币的可能端点:

@spotify_auth_bp.route("/refresh_token", methods=['GET', 'POST'])
def refresh_token():
        SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
        CLIENT_ID =   os.environ.get('SPOTIPY_CLIENT_ID')
        CLIENT_SECRET = os.environ.get('SPOTIPY_CLIENT_SECRET')

        code_payload = {
            "grant_type": "refresh_token",
            "refresh_token": refresh_token,
        }

        encode = 'application/x-www-form-urlencoded'
        auth = base64.b64encode("{}:{}".format(CLIENT_ID, CLIENT_SECRET).encode())
        headers = {"Content-Type" : encode, "Authorization" : "Basic {}".format(auth)} 

        post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
        response_data = json.loads(post_request.text)

        access_token = response_data["access_token"]
        refresh_token = response_data["refresh_token"]
        token_type = response_data["token_type"]
        expires_in = response_data["expires_in"]

        return access_token

Spotify 回调后处理我的代币的最佳方式是什么?

考虑到,一旦用户登录应用程序,他也将不间断地登录 Spotify,必须每 60 分钟刷新 Spotify 的访问令牌:

  • 授权代码是服务器到服务器的流程,仅用于保护秘密应用程序凭据,然后在前端拥有令牌是安全的吗?

  • 我是否应该将访问令牌和刷新令牌都存储在前端,并拥有无状态 JWT?

  • 我是否应该只保留临时访问令牌并在数据库中保留刷新令牌,并拥有有状态 JWT?

  • 我应该选择仅在服务器端保留的会话吗?

在这里处理我的敏感数据最安全的方法是什么?而且,考虑到上面的代码,怎么会这样呢?


这里有大量问题!让我们一一来看:

授权代码是服务器到服务器的流程,仅用于保护秘密应用程序凭据,然后在前端拥有令牌是安全的吗?

In the Authorization Code授予,你必须交换Authorization Code为了一个令牌。这是通过请求完成的/token (grant_type: authorization_code)并且它需要你的client_id and client_secret它秘密存储在您的服务器中(又名在您的 React Web 应用程序中不公开)。在这种情况下,它确实是服务器到服务器。

我是否应该将访问令牌和刷新令牌都存储在前端,并拥有无状态 JWT?

对于你的情况,我会说no。如果该令牌将用于在服务器端向 Spotify 发出一些 API 请求,请保持access_token and refresh_token服务器端.

但这样一来,它就不再是无国籍的了?的确。

“无国籍”你能做什么?

如果您确实想要/需要无状态令牌,恕我直言,您可以存储access_token在具有以下选项的 Cookie 中(并且是强制性的):

  • 安全:cookie 仅通过 HTTPS 发送
  • HttpOnly:无法从 Javascript 访问
  • SameSite:最好是严格的! (这里要看你是否需要CORS)

PRO:

  • 它是无状态的

CON:

  • 这可能是一块巨大的饼干。
  • 任何访问您计算机的人都可以获得 access_token,就像会话 cookie 一样。过期时间在这里很重要。也可以看看:https://stackoverflow.com/a/41076836/2437450 https://stackoverflow.com/a/41076836/2437450
  • 还有别的吗???受到挑战。

的情况下refresh_token.

我建议在服务器端存储刷新令牌,因为它通常是长寿命令牌。

当出现以下情况时该怎么办access_token过期?

当请求过期时access_token,您只需刷新即可access_token与服务器端存储refresh_token,完成工作,并返回一个新的响应access_token存储通过Set-Cookie header.

关于 JWT 的附加说明

如果您始终拥有 JWT 并将它们存储在 Http-Only cookie 中,您可能会说您没有任何方法知道您是否从 React 应用程序登录。 我已经用 JWT 尝试过一个非常好的技巧。

JWT 由 3 部分组成;标头、有效负载和签名。您真正想要在 cookie 中保护的是签名。事实上,如果你没有正确的签名,JWT 就没用了。因此,您可以做的就是拆分 JWT 并仅将签名设为 Http-Only。

在你的情况下它应该看起来像:

@app.route('/callback')
def callback():
    # (...)

    access_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJSYXBoYWVsIE1lZGFlciJ9.V5exVQ92sZRwRxKeOFxqb4DzWaMTnKu-VmhW-r1pg8E'

    a11n_h, a11n_d, a11n_s = access_token.split('.')

    response = redirect('http://localhost/about', 302)
    response.set_cookie('a11n.h', a11n_h, secure=True)
    response.set_cookie('a11n.d', a11n_d, secure=True)
    response.set_cookie('a11n.s', a11n_s, secure=True, httponly=True)

    return response

你会得到 3 个 cookie:

  • a11n.h:标题(选项:安全)
  • a11n.d:有效负载(选项:安全)
  • a11n.s:签名(选项:安全,仅 Http)

结果是:

  • a11n.dcookie 可以从你的 React 应用程序访问(你甚至可以从中获取用户信息)
  • a11n.scookie 无法从 Javascript 访问
  • 你必须重新组装access_token来自cookies在向 Spotify 发送请求之前在服务器端

重新组装access_token:

@app.route('/resource')
def resource():
    a11n_h = request.cookies.get('a11n.h') 
    a11n_d = request.cookies.get('a11n.d')
    a11n_s = request.cookies.get('a11n.s')

    access_token = a11n_h + '.' + a11n_d + '.' + a11n_s
    jwt.decode(access_token, verify=True)

我希望它有帮助!

免责声明:

代码示例需要改进(错误处理、检查等)。它们只是说明流程的示例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flask 和 React - Spotify 授权后处理令牌 的相关文章

随机推荐