最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

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

Python crifan 202浏览 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,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
62 queries in 0.110 seconds, using 18.74MB memory