How to get key from Azure KeyVault as a plain text? - azure

I have created key in Key Vault and manually imported private key in it. Now I want to retrieve using shell programing.
I have followed https://learn.microsoft.com/en-us/rest/api/keyvault/getkey/getkey and trying to retrieve the plain text but I am getting below error
curl https://test-poc-kv-31.vault.azure.net/keys/sftp/ec8368364d1844c908234396e8f50344e68?api-version=7.1
{"error":{"code":"Unauthorized","message":"Request is missing a Bearer or PoP token."}}
Not sure how to get the Bearer token for my URL?

The error message is quite clear, Request is missing a Bearar or Pop token.
Steps to create the token:
create a service principal using this command -
az ad sp create-for-rbac
grab appId from the output command and provide permissions to this service principal :
Grab password, appId and tenant from the above command and replace with the following:
curl --location --request POST 'https://login.microsoftonline.com/{TenantID}/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={appId}' \
--data-urlencode 'client_secret={password}' \
--data-urlencode 'scope=https://vault.azure.net/.default'
Get access_token from the responding command and pass it to this command:
curl -s "https://test-poc-kv-
31.vault.azure.net/keys/sftp/ec8368364d1844c908234396e8f50344e68?api-version=7.1" -H
"Authorization: Bearer %access_token%"
instead of using curl, you can use Azure CLI ( and make your life much easier ) :
az keyvault key show --name "%KEY_NAME%" --vault-name "VAULT_NAME"

Related

How to get a token from Azure AD OAuth2 implicit flow?

I am new in using command CURL to get token. I want command format to be used in CURL.
I have this information from customer :
Authentication:
Azure Active Directory OAuth2-Flow.
Type: oauth2/ Flow: implicit
Authorization URL:
Service Principal (Client ID & Client Secret)
Required Authorization/Scope: /provider/XXXX/XXX/BillingAccounts/{billingAccountId}
I tried this but , I am not getting the token , I got anerror :
curl --location --request POST 'https://xxxxxxxxxxxxxxxxx' \
--header 'Content-Type:application/json' \
--data-urlencode 'client_id=' \
--data-urlencode 'scope=' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_secret=' \
--data-urlencode 'code='
{"error":"invalid_request","error_description":"AADSTS9000410: Malformed JSON.\r\nTrace ID: daeb9aad9e73\r\nTimestamp: 2022-06-01 11:17:57Z","error_codes":[9000410],"timestamp":"2022-06-01 1
Can anyone help as soon as possible?
I reproduced the issue by keeping content_type as application/json.
I got the same error AADSTS9000410: Malformed JSON.
According to RFC 6749 - Section 4.1.3 definition ,the client
should make request to the token endpoint by sending the parameters
client_id ,grant_type,code, redirect uri, etc.. using the
application/x-www-form-urlencoded format per Appendix B with a character encoding of UTF-8 .
I tried changing the content type to application/x-www-form-urlencoded and recieved the token successfully.
CURL Request:
curl --location --request POST 'https://login.microsoftonline.com/06xxxxxxxxx/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=cxxxxxxxxxxxx698' \
--data-urlencode 'grant_type=' \
--data-urlencode 'client_secret=xxxxxxxxA' \
--data-urlencode 'scope=' \
--data-urlencode 'code=' \
--data-urlencode 'redirect_url='
Result:
So please change the content type to get token successfully.

how to generate storage account SAS token through curl

I need to generate a SAS token for blob container using curl command. Can someone guide me on how do i do that
i tried
curl -X PUT -T LICENSE.TXT --user client id of sp:client secret of sp https://axxx.blob.core.windows.net/etcd-backup
but this says that auth is not in proper format
Please refer the two links:
Get an access token and use it to call Azure Storage
Get a SAS credential from Azure Resource Manager to make storage calls
Code sample:
# get access token
response=$(curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fstorage.azure.com%2F' -H Metadata:true -s)
access_token=$(echo $response | python -c 'import sys, json; print (json.load(sys.stdin)["access_token"])')
echo The managed identities for Azure resources access token is $access_token
# get the SAS token with access token
curl https://management.azure.com/subscriptions/<SUBSCRIPTION ID>/resourceGroups/<RESOURCE GROUP>/providers/Microsoft.Storage/storageAccounts/<STORAGE ACCOUNT NAME>/listServiceSas/?api-version=2017-06-01 -X POST -d "{\"canonicalizedResource\":\"/blob/<STORAGE ACCOUNT NAME>/<CONTAINER NAME>\",\"signedResource\":\"c\",\"signedPermission\":\"rcw\",\"signedProtocol\":\"https\",\"signedExpiry\":\"<EXPIRATION TIME>\"}" -H "Authorization: Bearer $access_token"
Be sure to replace the <SUBSCRIPTION ID>, <RESOURCE GROUP>, <STORAGE ACCOUNT NAME>, <CONTAINER NAME>, and <EXPIRATION TIME> parameter values with your own values.

How to use azure translator with authorization token?

I want to use azure translator service with the Authorization token. There are plenty of resources explaining how to do it with subscription key but I could not found any resource explaining the use of authorization token. I can get the authorization token but when I send a request with it, the response status code is 401.
This is how I send the request:
curl POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer token' \
--data-raw '[{'\''Text'\'':'\''Hello World!'\''}]'
If you want to call Text Translation API with authentication token, please refer to the following steps
Get a token. If your service is global, the endpoint is https://api.cognitive.microsoft.com/sts/v1.0/issueToken
curl -v -X POST \
"https://YOUR-REGION.api.cognitive.microsoft.com/sts/v1.0/issueToken" \
-H "Content-type: application/x-www-form-urlencoded" \
-H "Content-length: 0" \
-H "Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY"
Besides, please note that an authentication token is valid for 10 minutes. The token should be reused when making multiple calls to the Translator. However, if your program makes requests to the Translator over an extended period of time, then your program must request a new access token at regular intervals (for example, every 8 minutes).
Call API
curl -X POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de' \
-H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
-H 'Content-Type: application/json' \
--data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp
For more details, please refer to here and here.

Testing AWS API Gateway with cURL

I do have a simple AWS API Gateway implementation protected by an AWS_IAM Authorization.
I just want to test from command line via cURL :
curl --location --request GET 'https://<API_ID>.execute-api.eu-west-1.amazonaws.com/stage?type=type&category=category&lc=lc&passprhase=passprhase&product=product'
--header 'Authorization: AWS4-HMAC-SHA256 Credential=<AWS_ACCESS_KEY>/20200127/eu-west-1/execute-api/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=<AWS_SECRET_ACCESS_KEY>' --header 'Content-Type: application/json' \
--data-raw '{"query":"","variables":{}}'
but keep getting the follow error :
Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header.
Can someone advice what am I doing wrong ?
AWS V4 signature authentication is supported in curl starting from version 7.75, so you should be able to call your AWS resource this way:
curl --location --request GET 'https://$API-ID.execute-api.eu-west-1.amazonaws.com/stage?type=type&category=category&lc=lc&passprhase=passprhase&product=product' \
--header 'Content-Type: application/json' \
--user $ACCESS_KEY:$SECRET_KEY \
--aws-sigv4 "aws:amz" \
--data-raw '{"query":"","variables":{}}'
Note that you may need to add in the --aws-sigv4 value your region and service.
For example: --aws-sigv4 "aws:amz:eu-west-2:execute-api"
You can find more documentation here: https://curl.se/libcurl/c/CURLOPT_AWS_SIGV4.html
And the documentation for the CLI option here: https://curl.se/docs/manpage.html#--aws-sigv4
AWS_IAM authorization uses Sigv4 and its calculation process requires values certain headers - Date being one of them. You are passing x-amz-date as a part of the "SignedHeaders" field, but not actually passing it with the other headers.
One way to create the right curl command to invoke an API with AWS_IAM would be to use Postman application. Add in the API URL and select "AWS Signature" under Authorization tab. You can then select the "Code" option and get the full curl command which would look something like this -
curl -X POST \
https://$API-ID.execute-api.$AWS_REGION.amazonaws.com/$STAGE/$RESOURCE \
-H 'authorization: AWS4-HMAC-SHA256 Credential=$ACCESS_KEY/20200128/$AWS_REGION/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=$SIGNATURE_VALUE' \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-H 'host: API-ID.execute-api.$AWS_REGION.amazonaws.com' \
-H 'postman-token: 15f9498e-95b7-f22b-eed9-016cdea07424' \
-H 'x-amz-date: $DATE_STAMP'
Create a Canonical Request for Signature Version 4
I could suggest to use awscurl which is much easier.
To install awscurl click here. For documentation you can refer here.
Example to call apigateway to call lambda for POST query is below.
awscurl --service execute-api -X POST -d '{ "alias" : "xyx", "type" : "LDAP" }' https://.execute-api.us-west-2.amazonaws.com/Prod/user/groups/get --region us-west-2 --access_key ACCESS_KEY --secret_key mfBl0YJRsXDue4C5F5B6rz1eUpQpA8uC24RtSnsg --security_token SECURITY_TOKEN

Microsoft Graph REST API invalid client secret

I have the following POST call I need to make. However, even if I provided the right client id and secret id, my call is getting rejected.
curl POST https://login.microsoftonline.com/f02....e3/oauth2/token
-H 'Content-Type: application/x-www-form-urlencoded' --data 'grant_type=authorization_code&redirect_uri=https://requestb.in/ac&
source=https://graph.microsoft.com&client_id=1e1....-913d9
&client_secret=YmbSFYz.....4Uk=&scope=mail.read&code=AaAAA........on0a569'
This is the error I receive:
curl: (6) Could not resolve host: POST
{"error":"invalid_client","error_description":"AADSTS70002:
Error validating credentials. AADSTS50012: Invalid client secret is
provided.\r\nTrace ID: 78d...a2b\r\nCorrelation ID:
01....ab2\r\nTimestamp: 2016-12-14 01:46:47Z","error_codes":[70002,50012],"timestamp":"2016-12-14 01:46:47Z","trace_id":"78d....a2b","correlation_id":"018.....ab2"}
How could I resolve this ?
EDIT: I am trying to achieve the second section(i.e getting token) in this documentation
The post you provided is leveraging AAD V2 endpoint. But according your code snippet, you were using V1 endpoint https://login.microsoftonline.com/f02....e3/oauth2/token. For acquire access token via V1 endpoint, you can refer to https://graph.microsoft.io/en-us/docs/authorization/app_authorization for more details.
For the V2 authorization endpoint, you may check out the endpoints you are using:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?...
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
And also it is required a v2.0 ad application:
This article assumes a v2.0 registration, so you'll register your app on the Application Registration Portal.
It was due to client_secret. It may contain special characters.
The encodeURIComponent() function encodes a URI component.
This function encodes special characters. In addition, it encodes the following characters: , / ? : # & = + $ #
Use the below one:
encodeURIComponent(client_secret);
In my case:
in configs You have to use the client secret "Value", not ID.
This Value is visible only when it is generated. So you can copy/paste it, in this moment.
See: https://learn.microsoft.com/en-us/answers/questions/370508/getting-34invalid-client-secret-is-provided34-erro.html
I am using the npm package:
Microsoft Azure Active Directory Passport.js Plug-In
with the v1 tenant-specific endpoint.
I was initially receiving the same error message after successfully logging into Microsoft: "Invalid Client Secret".
I was using the "Application ID" as the Client Secret. Then I discovered that you need to go onto the "Settings" tab in the Microsoft Azure Portal
Microsoft Azure
and create a new "Key". It doesn't matter what you name the key. When you click the "Save" button, the value of the key will be filled in the web form. Copy this right away, since it will not be displayed again if the web page is refreshed.
This is the "Client Secret" that you need to add to your configuration.
I hade the same problem today and with help of #muthu I sorted it out.
When client secret is generated with app registration in azure. The secret is plain. But when to use it in the rest call you must urlencode it.
Use an encoder like visual code or other. But it must be encoded else you ge the error
AADSTS7000215: Invalid client secret is provided.
You need to base 64 encode client_secret in the POST body.
For example (using curl):
# Authn details
LoginURL='https://login.microsoftonline.com'
TenantDomain='********.onmicrosoft.com'
ClientID='********'
ClientSecret='********'
# Endpoint details
Resource='https://graph.microsoft.com'
TenantGUID="********"
# Authenticate with OAuth v1
URL="$LoginURL/$TenantDomain/oauth2/token?api-version=1.0"
json=`
curl \
-s \
-k \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "$ClientID:$ClientSecret" \
-d "grant_type=client_credentials" \
-d "resource=$Resource" \
-d "client_id=$ClientID" \
--data-urlencode "client_secret=$ClientSecret" \
$URL \
| python -m json.tool
`
access_token=`echo $json | python -c 'import sys, json; print json.load(sys.stdin)["access_token"]'`
token_type=`echo $json | python -c 'import sys, json; print json.load(sys.stdin)["token_type"]'`
#echo "access_token:$access_token"
#echo "token_type:$token_type:"
# Access resource
URL="$Resource/v1.0/directoryRoles/$TenantGUID/members"
curl \
-s \
-k \
-X GET \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Authorization: $token_type $access_token" \
$URL \
| python -m json.tool

Resources