How can I authenticate with google cloud in Unity? - unity3d

I'm trying to use google automl object detection in a Unity project.
Here is the google curl command example:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/model-id:predict \
-d '{
"payload" : {
"image": {
"imageBytes" : "/9j/4AAQSkZJRgABAQAAAQ … "
},
}
}'
After some googling, I start to create a UnityWebRequest to test response:
WWWForm form = new WWWForm();
var postUrl = "https://automl.googleapis.com/v1beta1/projects/1043345783500/locations/us-central1/models/IOD1798528344157847552:predict";
using (UnityWebRequest www = UnityWebRequest.Post(postUrl, form))
{
www.SetRequestHeader("Authorization", #"Bearer $(gcloud auth application-default print-access-token)");
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else if (www.isDone)
{
Debug.Log(www.downloadHandler.text);
}
}
So the response from google is:
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
I understand that, I am not unauthenticated but couldn't understand how I can authenticate. Do I have to make an authentication request? How? Do I have to post something to get an access token? Then where should I send it?
I downloaded some credentials from google server but I really don't have any idea how to use it...

Related

Keycloak rest api 401 Unauthorized

I cannot get a normal rest api call to keycloak (v19) working.
What i want is that a "normal" user can query for all other KeyCloak users
What iam doing:
create realm "TestRealm"
create client "apiclient", with client authentication on and service account on
go to clients -> service account and assign roles "view-users" & "query-users" of the realm-management client to service account.
create user "TestUser"
assign roles "view-users" & "query-users" to the new user
Now i think everything is done and i can test the api:
Get the access token:
curl --location --request POST 'http://localhost:8081/realms/TestRealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=apiclient' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=TestUser' \
--data-urlencode 'password=ABC' \
--data-urlencode 'client_secret=ABC'
Token contains these values:
"realm_access": {
"roles": [
"offline_access",
"uma_authorization",
"default-roles-testrealm"
]
},
"resource_access": {
"realm-management": {
"roles": [
"view-users",
"query-groups",
"query-users"
]
},
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
Now the query for all users:
curl --location --request GET 'http://localhost:8081/admin/realms/TestRealm/users' \
--header 'Authorization: Bearer {{keycloak-bearer-token}}'
Response is "401 Unauthorized".
I dont know what iam doing wrong
EDIT: i had an issue somewhere else and these steps work exactly as expected

Bitbucket API - Unable to Generate Access Token from JWT

I'm using Bitbucket Connect App and getting JWT token from webhook event.
When I am using the latest JWT to get access token, the access token API returning blank in response.
API:
curl -X POST -H "Authorization: JWT {jwt_token}" \ https://bitbucket.org/site/oauth2/access_token \ -d grant_type=urn:bitbucket:oauth2:jwt
Example:
curl -X POST -H "Authorization: JWT ey*****XVCJ9.eyJpc3MiOi****asdfQ.**BBD**" \
https://bitbucket.org/site/oauth2/access_token \
-d grant_type=urn:bitbucket:oauth2:jwt
Response
{blank}
API Reference:
https://developer.atlassian.com/cloud/bitbucket/oauth-2/
Thanks
I had the same problem until I added the sub key to the payload. Set the value to the value received in clientKey during the app installation lifeycle event.
I followed this documentation to generate Access Token and it worked.
https://pawelniewiadomski.com/2016/06/06/building-bitbucket-add-on-in-rails-part-7/
Most of the Part for generating access token using Bitbucket Cloud API
def get_access_token
unless current_jwt_auth
raise 'Missing Authentication context'
end
# Expiry for the JWT token is 3 minutes from now
issued_at = Time.now.utc.to_i
expires_at = issued_at + 180
jwt = JWT.encode({
iat: issued_at,
exp: expires_at,
iss: current_jwt_auth.addon_key,
sub: current_jwt_auth.client_key
}, current_jwt_auth.shared_secret)
response = HTTParty.post("#{current_jwt_auth.base_url}/site/oauth2/access_token", {
body: {grant_type: 'urn:bitbucket:oauth2:jwt'},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'JWT ' + jwt
}
})
if response.code == 200
Response.new(200, response.parsed_response)
else
Response.new(response.code)
end
end

How can I create a pull request with github api?

The API is : /repos/{owner}/{repo}/pulls.
I used the correct token, and the request body is :
data = {
"base": "master",
"head": "owner:master",
"title": "title",
}
The head is like this:
{'Accept': 'application/vnd.github.v3+json', "Authorization": "token {}".format(git_token)}
Then I call the pull API. Returned 200.
<Response [200]>
Why? Maybe the request body wrong?
The Pull Request API specified the answer:
Status: 201 Created
Try and anddapt their example to your repository, to see if it does work:
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/octocat/hello-world/pulls \
-d '{"head":"head","base":"base"}'

Getting "HTTP method not allowed, supported methods: GET" when request is successful

I am working on a Akka-Http project in which I am writing a POST endpoint http://localhost:8080/api/v1/internal/admin/import which requires a header with an access token.
My curl request is as follows
curl --location --request POST 'http://localhost:8080/api/v1/internal/admin/import' \
--header 'Content-Type: application/json' \
--header 'Accept: text/plain' \
--header 'Authorization: correct-token' \
--data-raw '{
"id": 100,
"name": "test"
}'
When the access token is incorrect, I get the http response in the exact format that is expected
"status": {
"code": 403,
"error": "authorization_error",
"details": "Invalid token"
}
}
But as soon as I provide a correct token in the header, the http request is successful, but I get a weird message HTTP method not allowed, supported methods: GET.
Just before sending the correct response, I tried to print the json and its correct. My code looks as follows :
onComplete(futureR) {
case Success(result) =>
println(s"Success response json is ${Json.toJson(result)}")
complete(result)
case Failure(ex) => complete(
500 -> StatusResponse(ApiStatus(500, None, None))
)
}
The result I am getting on terminal is Success response json is {"status":{"code":0}} which is correct, however in Postman, I keep on getting the error HTTP method not allowed, supported methods: GET.
Any pointers to this problem ? TIA

Copy a public gdrive file to my account with curl

I tried to copy public gdrive files to my account by Gdrive API with a simple ps1 script and unix-tools for windows. (curl).
Worked out all required tokens and started to copy,download,delete files that I copied before.
The problem is, I found out that public shared files have different permissions
"capabilities": { "canCopy": true, "canEdit": false },
"editable": false, "copyable": true,
like this link for example:
drive.google.com/open?id=1ArIfiMSmBdlZQUm1cgHi8RRjhSCh8Rym
This is working fine by api request, but if I try to copy files with this permissions
"capabilities": { "canCopy": false, "canEdit": false },
"editable": false, "copyable": false,
drive.google.com/open?id=1cHAsF0D8zEp3LbVB4LmEQbJ3LdU8Cj7i
I get:
"reason": "forbidden",
"message": "Insufficient permissions for the specified parent.",
"locationType": "other",
"location": "parent.permissions" }],
"code": 403,
"message": "Insufficient permissions for the specified parent."
}
}
But in my browser I can rightclick taht file and simply make a copy.
So it seems just not possible by api requests.
But how can I do that by curl/http requests (with stored cookie or someting) ?
$UID = 'clientID.apps.googleusercontent.com'
$skey = 'clientsecret'
$readtoken = (Get-Content "$PSScriptRoot\refreshtoken.txt")
This is to create a fresh accesstoken from stored refreshtoken
$token = curl -d
"client_id=$UID&client_secret=$skey&refresh_token=$readtoken&grant_type=refresh_token"
https://accounts.google.com/o/oauth2/token | grep access_token
$string = $token.TrimStart(""access_token": `"")
$cleantoken = $string.TrimEnd("`",")
$drivefile = Read-Host -Prompt 'Put your Link here'
$driveID =
$drivefile.Substring(33)
$LINKS = curl --request POST
"https://www.googleapis.com/drive/v2/files/$driveID/copy" --header
"Authorization: Bearer $cleantoken" --header "Accept:
application/json" --header "Content-Type: application/json" --data
"{}" --compressed