{"id":8942,"date":"2023-09-13T01:41:01","date_gmt":"2023-09-12T17:41:01","guid":{"rendered":"\/?p=8942"},"modified":"2023-09-13T01:41:01","modified_gmt":"2023-09-12T17:41:01","slug":"fastapi%e5%9f%ba%e7%a1%80%ef%bc%9a7-%e5%ae%89%e5%85%a8%e8%ae%a4%e8%af%81-jwt","status":"publish","type":"post","link":"\/?p=8942","title":{"rendered":"FastAPI\u57fa\u7840\uff1a7.\u5b89\u5168\u8ba4\u8bc1-JWT"},"content":{"rendered":"<p><strong>JWT(Json Web Token)<\/strong><\/p>\n<p>\u5f53\u4e0b\u8f83\u591a\u9879\u76ee\u4f7f\u7528\u7684\u4e00\u79cd\u8ba4\u8bc1\u65b9\u5f0f\uff0c\u540e\u7aef\u901a\u8fc7\u52a0\u5bc6\u4fe1\u606f\uff08\u7528\u6237\u540d\/\u89d2\u8272\uff09\u8fd4\u56de\u4e00\u4e32\u79d8\u95fb\uff08\u5b9e\u9645\u53ef\u4ee5\u89e3\uff09\uff1b\u5ba2\u6237\u7aef\u901a\u8fc7\u8bf7\u6c42\u5934\u643a\u5e26\u8be5\u79d8\u95fb\uff0c\u540e\u7aef\u901a\u8fc7\u89e3\u5bc6\u6210\u529f\u4e0e\u5426\u6765\u786e\u8ba4\u662f\u5426\u662f\u7528\u6237<\/p>\n<h2>\u5bc6\u7801\u52a0\u5bc6<\/h2>\n<pre><code class=\"language-python\">&quot;&quot;&quot;\n\u5bc6\u7801\u52a0\u89e3\u5bc6\npip install passlib bcrypt \n&quot;&quot;&quot;\n\nfrom passlib.context import CryptContext\npwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)\n\ndef verify_password(plain_password: str, hashed_password: str) -&gt; bool:\n    &quot;&quot;&quot;\n    \u9a8c\u8bc1\u660e\u6587\u5bc6\u7801 vs hash\u5bc6\u7801\n    :param plain_password: \u660e\u6587\u5bc6\u7801\n    :param hashed_password: hash\u5bc6\u7801\n    :return:\n    &quot;&quot;&quot;\n    return pwd_context.verify(plain_password, hashed_password)\n\ndef get_password_hash(password: str) -&gt; str:\n    &quot;&quot;&quot;\n    \u52a0\u5bc6\u660e\u6587\n    :param password: \u660e\u6587\u5bc6\u7801\n    :return:\n    &quot;&quot;&quot;\n    return pwd_context.hash(password)<\/code><\/pre>\n<h2>\u751f\u6210JWT<\/h2>\n<p><a href=\"https:\/\/python-jose.readthedocs.io\/en\/latest\/\">python-jose \u2014 python-jose 0.2.0 documentation<\/a><\/p>\n<pre><code class=\"language-python\">def generate_token(username: str, expires_delta: Optional[timedelta] = None):\n    &quot;&quot;&quot;\n    \u751f\u6210token\n    :param username: \u7528\u6237\u540d\n    :param expires_delta: \u6709\u6548\u65f6\u957f\n    :return: \n    &quot;&quot;&quot;\n    to_encode = {&quot;sub&quot;: username}.copy()\n    if expires_delta:\n        expire = datetime.utcnow() + expires_delta\n    else:\n        expire = datetime.utcnow() + timedelta(\n            minutes=1\n        )\n    to_encode.update(dict(exp=expire))\n    encoded_jwt = jwt.encode(\n        to_encode, &quot;miyao&quot;, algorithm=&quot;HS256&quot;\n    )\n    return encoded_jwt<\/code><\/pre>\n<h2>\u89e3Token<\/h2>\n<pre><code class=\"language-python\">from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\nfrom fastapi import Depends, HTTPException\n\n# HTTPBearer \u5b9e\u9645\u4ece Request header\u4e2d\u53d6\u5230\u4e86 Token\nasync def check_token(security: HTTPAuthorizationCredentials = Depends(HTTPBearer())):\n    &quot;&quot;&quot;\u68c0\u67e5\u7528\u6237token&quot;&quot;&quot;\n    token = security.credentials\n    try:\n        payload = jwt.decode(\n            token, &quot;miyao&quot;, algorithms=[&quot;HS256&quot;]\n        )\n        username: str = payload.get(&quot;sub&quot;)\n        if fake_db.get(&quot;username&quot;) == username:\n            return fake_db\n    except JWTError:\n        raise HTTPException(status_code=401, detail=&quot;token g&quot;)\n<\/code><\/pre>\n<p><img src=\"https:\/\/lemon-guess.oss-cn-hangzhou.aliyuncs.com\/img\/1670148421797-ec60c30f-2798-4df1-8987-6413a2ed36f7.png\" alt=\"image.png\" \/><\/p>\n<p>ps\uff1a\u524d\u7aef\u8bf7\u6c42\u5934<\/p>\n<p><img src=\"https:\/\/lemon-guess.oss-cn-hangzhou.aliyuncs.com\/img\/1670148499937-18db310d-6d67-4494-8d35-f3e55a63776f.png\" alt=\"image.png\" \/><\/p>\n<p>ps\uff1a\u6700\u7ec8credentials \u5c31\u662f token\u4e32\uff0c\u5176\u5b9e\u5b8c\u5168\u53ef\u4ee5\u81ea\u5df1\u4f7f\u7528\u4e2d\u95f4\u4ef6\u6216\u8005\u4f9d\u8d56\u6ce8\u5165\u901a\u8fc7Request\u5bf9\u8c61\u81ea\u5df1\u5b9e\u73b0\uff0c\u56e0\u4e3a\u60f3\u8981\u63a5\u53e3\u6587\u6863\u4e0a\u7684\u9a8c\u8bc1\u6309\u94ae\u6240\u4ee5\u8fd9\u4e48\u505a<\/p>\n<pre><code class=\"language-python\">def check(request: Request):\n    &quot;&quot;&quot;\n    \u81ea\u5df1\u68c0\u67e5token\n    :param request:\n    :return:\n    &quot;&quot;&quot;\n    token = request.headers.get(&quot;x-token&quot;)\n    try:\n        payload = jwt.decode(\n            token, &quot;miyao&quot;, algorithms=[&quot;HS256&quot;]\n        )\n        username: str = payload.get(&quot;sub&quot;)\n        if fake_db.get(&quot;username&quot;) == username:\n            return fake_db\n    except JWTError:\n        raise HTTPException(status_code=401, detail=&quot;token g&quot;)<\/code><\/pre>\n<h2>\u767b\u5f55\u8ba4\u8bc1<\/h2>\n<pre><code class=\"language-python\"># \u9700\u8981\u767b\u5f55\n@app.get(&quot;\/info&quot;)\nasync def info(user=Depends(check_token)):\n    return user\n\n# \u9700\u8981\u767b\u5f55\n@app.get(&quot;\/user&quot;, dependencies=[Depends(check_token)])\nasync def infos():\n    return &#039;G&#039;<\/code><\/pre>\n<h2>\u63a5\u53e3\u6587\u6863<\/h2>\n<p><img src=\"https:\/\/lemon-guess.oss-cn-hangzhou.aliyuncs.com\/img\/1670148680883-a14f39ac-703e-49a2-b4c0-f241a3354413.png\" alt=\"image.png\" \/><\/p>\n<p><img src=\"https:\/\/lemon-guess.oss-cn-hangzhou.aliyuncs.com\/img\/1670148706325-1eebf552-6675-42aa-bd06-3855bfa1a54c.png\" alt=\"image.png\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>JWT(Json Web Token) \u5f53\u4e0b\u8f83\u591a\u9879\u76ee\u4f7f\u7528\u7684\u4e00\u79cd\u8ba4\u8bc1\u65b9\u5f0f\uff0c\u540e\u7aef\u901a\u8fc7\u52a0\u5bc6\u4fe1\u606f\uff08\u7528\u6237\u540d\/\u89d2\u8272\uff09\u8fd4\u56de\u4e00\u4e32\u79d8\u95fb\uff08\u5b9e\u9645\u53ef\u4ee5\u89e3\uff09\uff1b\u5ba2\u6237   \u2026 &#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0},"categories":[204],"tags":[116],"_links":{"self":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8942"}],"collection":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=8942"}],"version-history":[{"count":1,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8942\/revisions"}],"predecessor-version":[{"id":8943,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8942\/revisions\/8943"}],"wp:attachment":[{"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=8942"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=8942"},{"taxonomy":"post_tag","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=8942"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}