【问题标题】:Making a call to a Flask Restful API with invoke-restmethod and JWT auth使用 invoke-restmethod 和 JWT auth 调用 Flask Restful API
【发布时间】:2020-02-20 21:09:34
【问题描述】:

我有这个用 Flask (Python) 制作的 API,但我无法让 powershell 成功地向它发出 API 请求。问题不在于 API,因为我使用邮递员对其进行了测试,并且一切正常。更准确地说,当我添加 JWT 令牌身份验证时,它不能与 powershell 一起使用,在我的 api 中,创建、更新和删除函数受到 JWT 令牌身份验证的保护,而基本的读取函数根本没有身份验证。以下是我正在使用的 powershell 代码:

这是生成我的令牌的函数(该部分正在工作,请注意,出于安全目的,我从函数中删除了用户名和密码):

function get-token {
param (
    [Parameter(Position=0, Mandatory=$false)]
    [string]$user,
    [Parameter(Position=1, Mandatory=$false)]
    [string]$password
)
$body = @{
    username="$user"
    password="$password"
}
$jsonbody = $body | ConvertTo-Json
$uri = "https://codegenius.live/api/auth"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody -Headers $headers
$response.access_token
}

这个函数会生成一个这样的令牌:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODIyMzA2OTUsImlhdCI6MTU4MjIzMDM5NSwibmJmIjoxNTgyMjMwMzk1LCJpZGVudGl0eSI6MX0.8wZZJEGxV7P4ZzN23eZ3d5-MGJ00N5zKHuCZXn9XRuw

这是我试图拨打但不起作用的电话:

$body = @{
tpl_name="my template name"
tpl_subject="my template subject"
tpl_plaintext_content="bla bla bla"
tpl_html_content="bla bla bla"
} 

$authheader = "JWT " + (get-token)
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$headers.Add("Authorization",$authheader)
$jsonbody = $body | ConvertTo-Json
$uri = "https://codegenius.live/api/add-email"
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody -Headers $headers

请求响应消息是这个:

Invoke-RestMethod :
500 Internal Server Error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server         
is overloaded or
there is an error in the application.
Au caractère Ligne:25 : 17
+ ... $response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody  ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-    
RestMethod], WebEx
ception
+ FullyQualifiedErrorId : 
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

这很奇怪,因为正如我所说的它与 Postman 一起工作(见下图),我尝试用谷歌搜索这个问题,但我没有发现如何实际解决这个问题的线索。 编辑:图像显示在邮递员中我使用 http 而不是 https,这不是问题。在 powershell http 或 https 中没有任何作用!

【问题讨论】:

    标签: powershell rest api flask


    【解决方案1】:

    把你的线改成这样,

    $authheader = "JWT $(get-token)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      相关资源
      最近更新 更多