首页 > 解决方案 > shell脚本中的curl命令返回错误{“错误”:“bapigw-300无法授权访问资源”

问题描述

我正在尝试使用这个 shell 脚本执行 curl:

#!/bin/bash

curl -k -H "Content-Type:application/json" -d '{"username":"admin","password":"adminpw", "tenant":"master"}' https://localhost/tron/api/v1/tokens > /tmp/token.data

grep -Po '{\"token\":\"\K[^ ]...................' /tmp/token.data > /tmp/token

tokendetails=`cat /tmp/token`
for token in $tokendetails
do
  TOKEN=`echo $token`
done
userdetails=`cat /tmp/curloutput.txt | sed 's/{"clientInactivityTime"/\n{"clientInactivityTime"/g' | sed 's/\(.*\).\("firstName":[^,]*\)\(.*\)\("lastName":[^,]*\)\(.*\)\("email":[^,]*\)\(.*\)\("username":[^,]*\)\(.*\)/\2,\4,\6,\8/g' | grep username`

for user in $userdetails
do
  firstName=`echo $user | sed 's/,/\n/g' | grep firstName | sed 's/.*:"\([^"]*\).*/\1/g'`
  lastName=`echo $user | sed 's/,/\n/g' | grep lastName | sed 's/.*:"\([^"]*\).*/\1/g'`
  email=`echo $user | sed 's/,/\n/g' | grep email | sed 's/.*:"\([^"]*\).*/\1/g'`
  username=`echo $user | sed 's/,/\n/g' | grep username | sed 's/.*:"\([^"]*\).*/\1/g'`


curl -k -X POST "https://haxsne09/tron/api/v1/users" -H "accept: application/json" -H "Authorization: Bearer =${TOKEN}" -H "Content-Type: application/x-www-form-urlencoded" -d "first_name=${firstName}\&last_name=${lastName}\&email=${email}\&password=Tata123^\&username=${username}\&is_active=true"



echo $RESPONSE
done

我收到错误:

{"Error":"bpapigw-300 Cannot authorize access to resource: Could not authorize path for user identifier: Failed to get Roles for identifier: REST operation  failed 0 times: '[GET /api/v1/current-user][401] currentUserListUnauthorized  \u0026{Detail:Invalid token}'. This user is unauthenticated?"}

在执行之前我需要添加任何语法curl -k -X POST吗?

标签: shellcurlcommand-linescriptingusing

解决方案


您使用的Authorization标头不起作用。也许语法不是Bearer =aAbBcCdDeEfF0123456运行在服务器上的其他东西haxsne09,也许没有=@MarcoS 建议的那样。或者,您的 grep 命令可能返回一个太多字符(可能是一个流氓引号)。

我在下面重写了您的代码以提高可读性。你会注意到我:

  • 更改您的匹配组sed以仅捕获所需的部分并将它们放入变量中使用read. 我还使用了-E标志来避免使用\(\)
  • 删除了无用的for循环
  • 正确引用所有变量扩展
  • 添加了一些换行符以提高可读性
  • 删除了一些临时文件和相关的 cat 无用用途

这是更新的脚本:

#!/bin/bash

curl -k -H 'Content-Type:application/json' -d \
  '{"username":"admin","password":"adminpw", "tenant":"master"}' \ 
  https://localhost/tron/api/v1/tokens > /tmp/token.data

token=$(grep -Po '{"token":"\K[^ ]...................' /tmp/token.data)

IFS=, read -r firstName lastName email username < <(
  </tmp/curloutput.txt sed 's/{"clientInactivityTime"/\n&/' |
  sed -nE 's/.*."firstName":"([^"]*)".*"lastName":"([^"]*)").*"email":"([^"]*).*"username":"([^"]*)".*/\1,\2,\3,\4/p'
)

curl -k -X POST 'https://haxsne09/tron/api/v1/users' -H 'accept: application/json' \
  -H "Authorization: Bearer $token" -H "Content-Type: application/x-www-form-urlencoded" -d \
  "first_name=$firstName&last_name=$lastName&email=$email&password=Tata123^&username=$username&is_active=true"

echo

推荐阅读