I'm trying to get person data using following .net(installed application) code. but it gives me error forbidden
UserCredential credential;
using (var stream = new FileStream("path to the secrets json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] {
PlusDomainsService.Scope.PlusCirclesRead,
PlusDomainsService.Scope.PlusCirclesWrite,
PlusDomainsService.Scope.PlusLogin,
PlusDomainsService.Scope.PlusMe,
PlusDomainsService.Scope.PlusMediaUpload,
PlusDomainsService.Scope.PlusProfilesRead,
PlusDomainsService.Scope.PlusStreamRead,
PlusDomainsService.Scope.PlusStreamWrite,
PlusDomainsService.Scope.UserinfoEmail,
PlusDomainsService.Scope.UserinfoProfile
},
"user", CancellationToken.None, new FileDataStore("Domains.SampleApi"));
}
var service = new PlusDomainsService(new BaseClientService.Initializer
{
ApplicationName = "API Sample",
HttpClientInitializer = credential
});
var me = await service.People.Get("me").ExecuteAsync();<-- this line gives error
I cannot even run the sample code here
https://developers.google.com/+/domains/api/people/get#try-it
it gives me following error
Cache-Control: private, max-age=0
Content-Type: application/json; charset=UTF-8
Date: Thu, 25 Sep 2014 14:24:56 GMT
Expires: Thu, 25 Sep 2014 14:24:56 GMT
Server: GSE
Transfer-Encoding: chunked
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
Note: I tried using website and installed application but both giving me same error.
Related
First of all, I would like to apologize for my really bad english, if something is not understandable, then reask please.
When I try POST with /api/account/regapi in Swagger then with too short password it gives error 200, but with correct length it gives error 500, while debugging it shows correct parameters at AuthDTO model, but still shows error 500 with correct data.
Response header returned by false data(incorrect password length):
{
"$id": "1",
"succeeded": false,
"errors": [
{
"$id": "2",
"code": "PasswordTooShort",
"description": "Passwords must be at least 6 characters."
}
]
}
Response header with incorrect password
access-control-allow-origin: *
content-type: application/json; charset=utf-8
date: Sat, 26 May 2018 13:54:06 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Response header with correct data:
content-type: text/html; charset=utf-8
date: Sat, 26 May 2018 14:03:59 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Registration in AccountController
public async Task<IActionResult> RegApi(AuthDTO model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
return Ok(result);
}
return BadRequest();
}
public class AuthDTO
{
public string Email { get; set; }
public string Password { get; set; }
}
I think the is problem is in _usermanager, because error 500 is starting to show up there
Followed
OAuth example
successfully getting bearer token, but response is:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Vary: X-Origin
Vary: Referer
Vary: Origin
Vary: Accept-Encoding
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: hq=":443"; ma=2592000; quic=51303433; quic=51303432; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="43,42,41,39,35"
Transfer-Encoding: chunked
Accept-Ranges: none
Cache-Control: private
Date: Thu, 03 May 2018 13:29:53 GMT
Server: ESF
WWW-Authenticate: Bearer realm="https://accounts.google.com/"
Content-Type: application/json; charset=UTF-8
}}
using a service account with 'ML Engine Developer' Role.
Here is the code:
var url = $"{googleapiprojecturl}/models/{modelname}/versions/{version}:predict";
GoogleCredential credential;
using (Stream stream = new FileStream(#"C:\serviceacctkey.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = GoogleCredential.FromStream(stream);
}
var bearer_token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync(url);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token);
var content = new StringContent(payloadJsonString, Encoding.UTF8, "application/json");
var responseMessage = await client.PostAsync(url, content);
responseMessage.EnsureSuccessStatusCode();
where googleapiprojecturl = https://ml.googleapis.com/v1/projects/{projectID}
as Chris suggested above, as comment on the question, the answer was scope on the credential before asking for token:
credential = GoogleCredential.FromStream(stream).CreateScoped(new[] { CloudMachineLearningEngineService.Scope.CloudPlatform });
I haven't done this in C#, but I also had trouble in Python with the following similar code:
# Doesn't work
# creds = GoogleCredentials.from_stream(SERVICE_ACCOUNT_FILE)
In Python, the following worked instead:
from oauth2client import service_account
creds = service_account.ServiceAccountCredentials.from_json_keyfile_name('key.json', SCOPES)
creds.get_access_token()
In C#, it looks like you would use the ServiceAccountCredentials class.
I need to call an API from AppService by uri.
This is my API:
public ApiOutputBase Test_AddStudent(string name, int age, string address)
{
return new ApiOutputBase
{
Result = new Result { Status = true, Message = "OK,Test_AddStudent Done!" },
OuputValues = new List<object>() { name, age, address }
};
}
I use this Function to call it:
public async Task<bool> TestCallApi()
{
var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
// Call api success
if (response.IsSuccessStatusCode)
{
}
return true;
}
I used Swagger to call Test_AddStudent successfully. The testJson was copied from Swagger when I call Test_AddStudent successfully.
After that, I used Swagger to call TestCallApi without any error, but when I tried to debug the value of HttpResponseMessage, it showed this error:
{
StatusCode: 400,
ReasonPhrase: 'Bad Request',
Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers: {
Pragma: no-cache
Cache-Control: no-store, no-cache
Date: Tue, 31 Oct 2017 02:12:45 GMT
Set-Cookie: Abp.Localization.CultureName=en; expires=Thu, 31-Oct-2019 02:12:45 GMT; path=/
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 405
Content-Type: application/json; charset=utf-8
Expires: -1
}
}
Have I missed something?
I finally found the root cause: I passed the wrong input to the api:
Wrong:
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
Correct:
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent?name=MyName&age=25&address=MyAdress", "");
I am having a big problem when trying to authenticate to QuickBlox's server using a Token.
The method I use is:
public static async Task<LoginResponse> GetLoginResponseAsync(string email, string password)
{
LoginResponse result = null;
using (var client = new HttpClient())
{
string token = QbProvider.SessionResponse.Session.Token;
LoginRequest request = new LoginRequest()
{
Email = email,
Password = password
};
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, LoginUrlRequest))
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("QB-Token", token);
using (var response = await client.SendAsync(requestMessage))
{
string json = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<LoginResponse>(json);
}
}
}
return result;
}
The server's response is:
{"errors":["Token is required"]}
And the headers (debugging) in the client object are:
{
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Date: Thu, 01 Jun 2017 12:05:29 GMT
QuickBlox-REST-API-Version: 0.1.1
Server: openresty/1.9.15.1
Status: 401 Unauthorized
Strict-Transport-Security: max-age=31536000
WWW-Authenticate: OAuth realm=users
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 584a0dca-fc44-4114-9626-327ac1729f67
X-Runtime: 0.003430
X-XSS-Protection: 1; mode=block
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Content-Length: 32
}
}
When I use the Token in Postman, the server's response is successfull.
Do you know what am I doing wrong?
Thank you so much in advance!
Regards.
Try adding your token header using requestMessage.Headers.Add("QB-Token", token) instead of your Authorization one – by #dukedukes
I'm trying to upload a video (resumable) to YouTube via the API in C# (not through client).
I'm following these instructions on using resumable upload protocol
However when I make the attempt I get back an Parse Error.
Here is my request:
POST /upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails&key={api_key} HTTP/1.1
Host: www.googleapis.com
X-upload-content-length: 5346742
X-upload-content-type: video/*
Content-type: application/json; charset=UTF-8
Content-length: 277
Authorization: Bearer {access_token}
{
"snippet": {
"title": "My video title",
"description": "This is a description of my video",
"tags": ["cool", "video", "more keywords"],
"categoryId": 22
},
"status": {
"privacyStatus": "public",
"embeddable": True,
"license": "youtube"
}
}
Here is the response:
HTTP/1.1 400 Bad Request
Alternate-protocol: 443:quic
Content-length: 171
Via: HTTP/1.1 GWA
X-google-cache-control: remote-fetch
Server: HTTP Upload Server Built on Sep 30 2013 10:58:35 (1380563915)
Date: Wed, 02 Oct 2013 21:38:10 GMT
Content-type: application/json
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Anyone have any ideas?
The parse error is due to True being written with a big T.
(using the beta library is not an option for me becuase of Unity. .NET 2.0..)
why dont u use Google GData Youtube Api for .NET ?
string developerkey = "developerKey";
YouTubeRequestSettings settings = new YouTubeRequestSettings("Somethinghere", developerkey, "googleUserName", "googlePassWord");
YouTubeRequest request = new YouTubeRequest(settings);
newVideo.Title = "Video Title Here || ArgeKumandan";
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "cars, funny";
newVideo.Description = "My description";
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema));
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(#"D:\video ArgeKumandan.flv", "video/flv");
createdVideo = request.Upload(newVideo);