最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中如何模拟用户登录和传递JWT的token以获取访问API的权限

Python crifan 3456浏览 0评论

折腾:

【已解决】把文本格式的剧本内容用Python批量导入后台系统

期间,需要去模拟用户登录

【总结】

然后发现还是比较简单的:

<code>
Username = "username"
Password = "pwd"

ApiHost = "http://localhost"

Port = 65000
ApiVersion = "/api/v1"
ApiPrefix = ApiHost + ":" + str(Port) + ApiVersion # http://localhost:65000/api/v1/

GetJwtTokenUrl = ApiPrefix + "/jwt-token-auth/" # http://localhost:65000/api/v1/jwt-token-auth/
CreateScriptUrl = ApiPrefix + "/scripts/" # http://localhost:65000/api/v1/scripts/

gJwtToken = ""
gHeaders = {
  "Authorization": "",
}


def generateTokenAndUpdateHeader():
  global gJwtToken, gHeaders

  postBody = {
    "username": Username,
    "password": Password,
  }
  logging.info("GetJwtTokenUrl=%s, postBody=%s", GetJwtTokenUrl, postBody)
  getTokenResp = requests.post(GetJwtTokenUrl, data=postBody)
  logging.info("getTokenResp=%s", getTokenResp)
  respJson = getTokenResp.json()
  logging.info("respJson=%s", respJson)
  gJwtToken =  respJson["token"]
  logging.info("gJwtToken=%s", gJwtToken)

  if gJwtToken:
    gHeaders["Authorization"] = "JWT " + gJwtToken
    logging.info("gHeaders=%s", gHeaders)

# 后续调用API接口时,传递带JWT xxx的headers即可:
logging.info("curScriptDict=%s", curScriptDict)
saveScriptResp = requests.post(CreateScriptUrl, headers=gHeaders, data=curScriptDict)
logging.info("saveScriptResp=%s", saveScriptResp)
</code>

一般的JWT的token,大概长这样:

<code>2018/07/17 11:22:29 BatchImportScript.py:77 INFO gHeaders={'Authorization': 'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.xxxxxxxxx.hklGrByjU-v_xxxxx_-dc'}
</code>

转载请注明:在路上 » 【已解决】Python中如何模拟用户登录和传递JWT的token以获取访问API的权限

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.200 seconds, using 22.20MB memory