Device code flow: Microsoft.Identity.Client.MsalServiceException: AADSTS70011: The provided value for the input parameter 'scope' is not valid - azure

This question is not a duplicate of AADSTS70011: The provided value for the input parameter 'scope' is not valid because that post didn't solve my problem.
This is the code:
using Microsoft.Identity.Client;
var tenantId = "common";
var clientId = "475c75f3-9fdc-4d23-8956-104342a43740";
var apiUrl = "https://graph.microsoft.com";
var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(
new PublicClientApplicationOptions{
TenantId="common",
ClientId=clientId
}
)
.WithRedirectUri("http://localhost")
.Build();
string[] scopes = new string[] {$"{apiUrl}/.default"};
var result = await app.AcquireTokenWithDeviceCode(
scopes,
deviceCodeResult =>
{
Console.WriteLine(deviceCodeResult.Message);
return Task.FromResult(0);
}
).ExecuteAsync();
Console.WriteLine(result.AccessToken);
This is the error message that I get:
Unhandled exception. MSAL.NetCore.4.44.0.0.MsalServiceException:
ErrorCode: invalid_scope
Microsoft.Identity.Client.MsalServiceException: AADSTS70011: The provided value for the input parameter 'scope' is not valid. One or more scopes in 'https://graph.microsoft.com/.default offline_access profile openid' are not compatible with each other.
Trace ID: 977837bb-49bb-448a-990f-f640ee518500
Correlation ID: f6483ab1-e0be-43b0-8859-086b28ac6ea2
Timestamp: 2022-06-12 00:26:35Z
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext, Boolean addCommonHeaders, Func`2 onBeforePostRequestHandler)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ICoreLogger logger)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ICoreLogger logger)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.DeviceCodeRequest.WaitForTokenResponseAsync(DeviceCodeResult deviceCodeResult, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.DeviceCodeRequest.WaitForTokenResponseAsync(DeviceCodeResult deviceCodeResult, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.DeviceCodeRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenWithDeviceCodeParameters deviceCodeParameters, CancellationToken cancellationToken)
at Program.<Main>$(String[] args) in /home/adrian/azure/Program.cs:line 16
at Program.<Main>(String[] args)
StatusCode: 400
According to this documentation, the device code flow can be reproduced with this script:
TENANT_ID='common'
CLIENT_ID='475c75f3-9fdc-4d23-8956-104342a43740'
output=$(
curl -s https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/devicecode \
-X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d "client_id=${CLIENT_ID}&scope=user.read%20openid%20profile"
)
echo "URL: $(jq -r '.verification_uri' <<<$output)"
echo "CODE: $(jq -r '.user_code' <<<$output)"
read
output=$(
curl -s https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token \
-X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d "grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=${CLIENT_ID}&device_code=$(jq -r '.device_code' <<<$output)"
)
curl -s https://graph.microsoft.com/v1.0/me \
-H "Authorization: Bearer $(jq -r '.access_token' <<<$output)" | jq
However, for some reason when I execute the script I don't get any errors. Why?
EDIT: I thought I was using the .default scope in the script too, my bad. This is the updated code, which now returns yet another different error:
TENANT_ID='common'
CLIENT_ID='475c75f3-9fdc-4d23-8956-104342a43740'
output=$(
curl -s https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/devicecode \
-X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d "client_id=${CLIENT_ID}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default"
)
echo "URL: $(jq -r '.verification_uri' <<<$output)"
echo "CODE: $(jq -r '.user_code' <<<$output)"
read
curl -s https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token \
-X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d "grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=${CLIENT_ID}&device_code=$(jq -r '.device_code' <<<$output)"
and this is the error I get:
{
"error": "invalid_scope",
"error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. One or more scopes in 'https://graph.microsoft.com/.default' are not compatible with each other.\r\nTrace ID: 9d5809b7-32ad-4c18-a8d8-4ac49a439100\r\nCorrelation ID: eb10447d-fce6-4a33-b669-c62924f4e08a\r\nTimestamp: 2022-06-12 09:59:54Z",
"error_codes": [
70011
],
"timestamp": "2022-06-12 09:59:54Z",
"trace_id": "9d5809b7-32ad-4c18-a8d8-4ac49a439100",
"correlation_id": "eb10447d-fce6-4a33-b669-c62924f4e08a"
}

Related

BASH CURL pass json data for POST request

im trying try to POST a request in a BASH script but somehow, my json data cant be find bellow is my code.
header=$(curl -sb -H "Accept: application/json" "http://localhost:4040/api/tunnels")
# this is json format
tunnels=`echo "$header"`
echo "{'token':'xoxp-token-key','channel':'hybridteam','appname':'Server Unit', 'data': ${tunnels}}"
header2=$(curl -H "Content-type: application/json" -H "Accept: application/json" -sb -d "{'token':'token-key-here','channel':'hybridteam-ngrok','appname':'This is testing PC', 'data': ${tunnels}}" -X POST "https://localhost:8080")
success=`echo "$header2"`
echo $success
And my Server gets the data like this
$data = json_decode(isset($_POST['data'])? $_POST['data'] : $_GET['data']);
$token = isset($_POST['token'])? $_POST['token'] : $_GET['token'];
$channel = isset($_POST['channel'])? $_POST['channel'] : $_GET['channel'];
BUT on my server I keep getting this response
<br /> <b>Notice</b>: Undefined index: data in <b>C://xampp/htdocs/server/index.php</b> on line <b>30</b><br /> <br /> <b>Notice</b>: Undefined index: token in <b>C://xampp/htdocs/server/index.php</b> on line <b>31</b><br /> <br /> <b>Notice</b>: Undefined index: channel in <b>C://xampp/htdocs/server/index.php</b> on line <b>32</b><br />
Pls Im new to bash scripting, need your help.
Thanks.
json supports double quotes
curl -H "Content-type: application/json" \
-H "Accept: application/json" -sb \
-d "{\"token\":\"token-key-here\",\"channel\":\"hybridteam-ngrok\",\"appname\":\"This is testing PC\", \"data\": ${tunnels}}" \
-X POST "https://localhost:8080"
and you need to read raw POST body and convert it either into object or to array.
$raw = file_get_contents("php://input");
$data = json_decode($raw,true);
$token = isset($data['token'])? $data['token'] : null;
$channel = isset($data['channel'])? $data['channel'] : null;

parse error: Invalid numeric literal at line 1, column 8

I am trying to get a token to some site by using curl. It looks like request is done correctly because I have to wait a bit for response however something is during deserialization because I always got error: parse error: Invalid numeric literal at line 1, column 8
This is how script looks like:
TOKEN=$(curl --request POST \
--url 'https://${DOMAIN_NAME}/getmy/token' \
--header 'content-type: application/json' \
--data '{"grant_type":"password", "username":"${USER_EMAIL}",
"password":"${USER_PASSWORD}",
"audience":"https://localhost:8443/my-composite-service", "scope":"openid
email test:read test:write", "client_id": "${CLIENT_ID}",
"client_secret": "${CLIENT_SECRET}"}' -s | jq -r .access_token)
Is it because of jq?
What is more I am sure that env variables are there, even with hard coded values the same error will be thrown.
Thank you in advance
Some hints:
Do not put everything in one line, make it readable instead.
Structure your code with functions.
Do error handling.
Use Bash's debugging functionality.
Do not build JSON with string concatenation, use JQ instead, because only JQ quotes JSON data correctly. A password may contain quoting characters.
An example:
set -eu
set -x
USER_EMAIL="user#domain.org"
USER_PASSWORD="password"
CLIENT_ID="id"
CLIENT_SECRET="secret"
DOMAIN_NAME="domain.org"
data()
{
local template='
{
"grant_type": "password",
"username": $username,
"password": $password,
"audience": "https://localhost:8443/my-composite-service",
"scope": "openid email test:read test:write",
"client_id": $client_id,
"client_secret": $client_secret
}'
if jq <<<null -c \
--arg username "${USER_EMAIL}" \
--arg password "${USER_PASSWORD}" \
--arg client_id "${CLIENT_ID}" \
--arg client_secret "${CLIENT_SECRET}" \
"$template"
then
return
else
printf "ERROR: Can not format request data." >&2
exit 1
fi
}
post()
{
if curl --request POST \
--url 'https://${DOMAIN_NAME}/getmy/token' \
--header 'content-type: application/json' \
--data "$1" \
-s
then
return
else
printf "ERROR: Can not send post request." >&2
exit 1
fi
}
token()
{
if jq -r .access_token
then
return
else
printf "ERROR: Can not parse JSON response." >&2
exit 1
fi
}
TOKEN="$(post "$(data)" | token)"

how to use the simple-oauth2 library to make request application/x-www-form-urlencoded?

i have some code which perfectly work through mac terminal and giving me token from website
curl -XPOST "https://link.com/oauth/access_token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: 1.0" \
--data-urlencode "grant_type=client_credentials" \
--data-urlencode "client_id=myawesomeapp" \
--data-urlencode "client_secret=abc123" \
--data-urlencode "scope=read write"
I want to do request through nodejs without curl request. website giving link on npm library simple-oauth2, but my code does not work.
my not working version of this
const credentials = {
client: {
id: 'myawesomeapp',
secret: 'abc123'
},
auth: {
tokenHost: 'https://link.com',
tokenPath: '/oauth/access_token'
},
http: {
'headers.authorization': 'headers.Accept = application/x-www-form-urlencoded'
}
};
oauth2 = oauth2.create(credentials);
oauth2.accessToken.create()
If it's an x-www-form-urlencoded content type, you'll probably need to also update the authorisation method in your options to form (its default is header). I.e.
const credentials = {
/*
your existing config
*/
options: {
authorizationMethod: 'body'
}
}
Hopefully that should do the trick...

POST request containing CSR fails in Bash

I've written a bash script that sends a POST request to a server. The request contains a certificate signing request and the server signs it and returns a certificate.
When I copy and paste the CSR text in the POST's body, then the POST request is successful. But when I read the CSR from a variable, then the POST request fails. I've attached a snippet of the program below.
PROGRAM - Bash
openssl req -new -newkey rsa:2048 -nodes -out cert.csr -keyout priv.key -subj "/C=MyCountry/ST=MyState/L=MyCity/O=MyCompany/OU=MyDept/CN=MyComp"
if [ $? == 0 ]; then
csr=$(<cert.csr)
fi
response=$(curl -o - -s -w "%{http_code}\n" -X POST \
https://xxx.xxx.com/URI-END-POINT \
-H "authorization: $token" \
-H "content-type: application/json" \
-d '{
"digicert": {
"csr": "'$csr'",
"profileName": "pn123",
"signatureHash": "sh123",
"userPrincipalName": "pn123",
"validationScopeId": "vsi123"
},
"IccId": "sim123",
"MacAddress": "mac123"
}')
if [ $?==0 ]; then
status=$(echo $response | tail -c 4)
if [ "$status" == "$http_success" ]; then
echo -e "Request for certificate SUCCESS"
else
echo -e "Request for certificate FAILED with return code $status"
fi
else
echo -e "Request for certificate FAILED"
fi
OUTPUT - Bash
curl: option -----END: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
In the above script, if I replace the line "csr": "'$csr'", with "csr": "----BEGIN CERTIFICATE REQUEST---- XXXXXXX ----END CERTIFICATE REQUEST----", then this will work fine.
Can you help me debug this?
Thanks!
Maybe the string in $csr is being evaluated, like if put in double quotes and the resulting string is something different than expected.
For start, try to see if $csr is same as "$csr".
To post the contents of a file, use jq to generate the JSON blob for you: this will take care of any necessary quoting automatically. The output of jq is pipe directly to curl by using the #- argument for the -d option. (A #-prefixed string indicates the name of a file curl should read from; - is the alias for standard input.)
response=$(jq -n --arg csr "$(<csr)" '{
digicert: {
csr: $csr,
profileName: "pn123",
signatureHash : "sh123",
userPrincipalName: "pn123",
validationScopeId: "vsi123"
},
IccId: "sim123",
MacAddress: "mac123"
}' |
curl -o - -s -w "%{http_code}\n" -X POST \
https://xxx.xxx.com/URI-END-POINT \
-H "authorization: $token" \
-H "content-type: application/json" \
-d #-
)

Request body is not properly feined in loadtest

I was using loadtest for load tetsing of my node app. I had issue sending post requests via loadtest. The request is of the form:
loadtest http://localhost:7000/eth/checkEthBalance -T "application/x-www-form-urlencoded" -H "application/x-www-form-urlencoded" -m "POST" --data '{"accountAddress":"0x62720366ef403c9891e2bfbd5358ee3c8a57b113"}' -n 1
But in req.body, I am getting:
{ '{"accountAddress":"0x62720366ef403c9891e2bfbd5358ee3c8a57b113"}': '' }
instead of:
{"accountAddress":"0x62720366ef403c9891e2bfbd5358ee3c8a57b113"}
However a curl request workd fab:
curl -X POST \
http://localhost:7000/eth/checkEthBalance \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-H 'postman-token: 0bf637f7-2037-c4ca-29a7-cc2310786317' \
-d accountAddress=0x62720366ef403c9891e2bfbd5358ee3c8a57b113
DOn't know what's wrong with loadtest. Any help?
Here how I did it, you need to pass -T 'application/json'
Sample : loadtest -P '{"name" : "ashok dey", "email" : "ashokdey#gmail.com", "password" : "password123"}' -c 100 --rps 2000 http://localhost:3434/register -T 'application/json'
You have to pass the same when you are passing a file containing the post data.

Resources