API端点授权无法通过Powershell脚本运行

时间:2019-08-01 09:50:57

标签: rest powershell asp.net-core jwt bearer-token

我正在尝试编写一个简单的脚本,该脚本由服务器的任务调度程序通过Powershell调用。

脚本看起来像这样。

$params = @{
    "username" = "name";
    "password" = "password";
}

$token = Invoke-RestMethod -Method POST -Uri "http://localhost:5000/api/login" -Body ($params|ConvertTo-Json) -ContentType "application/json"

echo $token //The token gets printed correctly

$headers = @{
    Authorization = "Bearer " +$token
}     

Invoke-RestMethod -Method Post -Uri "http://localhost:5000/api/somemethod" -Headers $headers

登录名被完美调用-带有注释的somemethod

[Authorize(Roles = "admin")]
[HttpPost("somemethod/")]
public async Task<IActionResult> SomeMethod()
{
        //Do something
        return NoContent(); 
}
另一方面,

获得以下控制台输出。

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 POST https:/localhost:5001/api//somemethod application/x-www-form-urlencoded 0
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Route matched with {action = "SomeMethod", controller = "Api"}. Executing controller action with signature System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] SomeMethod() on controller Api.Controllers.ApiController (Api).
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
      AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Api.Controllers.ApiController.SomeMethod(Api) in 5.637ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 10.6572ms 401

我在这里想念什么?

编辑:当我调试中间件时,请求按预期发送令牌。我将对此进行更深入的研究,并在需要时提供进一步的信息。

enter image description here

1 个答案:

答案 0 :(得分:0)

在未指定const fruits = array.filter(o => o instanceof Fruit_obj); return fruits.length; POST的情况下,我看到了很多问题。

content-type

或您正在Invoke-RestMethod -Method Post -Uri "http://localhost:5000/api/somemethod" -Headers $headers -Body $data -ContentType "application/json" 使用的任何content-type