When I am inserting the events into the Google calendar of my google account but it was throwing the 401 unauthorized error.
I am using the following code to add events to the calendar.
Event _calendarEvent = new Event()
.setSummary(_calendarData.get(0).get_calenderTitle())
.setDescription("AppName");
CommonUtility.convertDateFormat(_calendarData.get(0)
.get_startTime(), "yyyy-MM-dd HH:mm",
"yyyy-MM-dd'T'HH:m:ssZZZZZ");
DateTime startDateTime = new DateTime(CommonUtility.convertDateFormat(_calendarData.get(0).get_startTime(), "yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm:ssZZZZZ"));
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone(tz.getID());
start.setDateTime(startDateTime);
_calendarEvent.setStart(start);
DateTime endDateTime = new DateTime(CommonUtility.convertDateFormat(_calendarData.get(0).get_endTime(), "yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm:ssZZZZZ"));
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone(tz.getID());
end.setDateTime(endDateTime);
_calendarEvent.setEnd(end);
//401 unauthorized exception thrown by the insert method below.
Event _eventLogged = mService.events().insert(_credential.getSelectedAccountName(), _calendarEvent).execute();
The I am facing is shown below.
{
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
Authorization code
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("AppName")
.build();
GoogleCredential code
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
Related
Returned in custom permission validation
// custom status code
context.Result = new StatusCodeResult(701);
Set up in the middleware
if (httpContext.Response.StatusCode == 701 && httpContext.Request.Method != "OPTIONS")
{
var body = new ResultDTO<string>()
{
Code = 701,
MsgKey = "Jwt Token Expired",
Message = "Jwt token expired, permission verification failed."
};
var bodys = JsonConvert.SerializeObject(body);
var bytes = Encoding.UTF8.GetBytes(bodys);
await httpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
error
// console
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM69HI8TSMUD", Request id "0HM69HI8TSMUD:00000002": An unhandled exception was thrown by the application.
System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 54).
//http request
cors error
The reasons are explained here: https://stackoverflow.com/a/47232876
And in the ExceptionHandleMiddleware the try... .catche cannot intercept
I need help
Required.
Custom status codes
Customize the return result
i am wondering if there is a way to prevent a response to return keys in object that are null or null equivalent. I have for example a Response envelope and then the data payload and a sample response looks like this.
{
"success": true,
"errorCode": "",
"message": "JWT Token succesfull created",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidXNlcmlkIiwiU2NvcGUiOlsiQVRUQ1NSIiwiQVRUTFNSIl0sIm5iZiI6MTU4NDc0MjIzMiwiZXhwIjoxNTg0NzQzOTcyLCJpc3MiOiJodHRwOi8vc29hcGFwaS5wZ3RlbC5uZXQiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjU3NDY0In0.dWuETKdlfX4VzwWEP5XafZOpnFmSSCchQHUHi5GZ99E",
"expiration": "0001-01-01T00:00:00",
"scope": null
}
}
In this case expiration and scope are null expiration is a DateTime field.
Here is how i get to this response
Dim myResponse As New jsonResponse
myResponse.success = True
meResponse.errorCode = ""
myResponse.message = "JWT Token succesfull created"
Dim authCheck As New JSONWebTokenUtil
Dim accessList As New List(Of String)
accessList.Add("Sample1")
Dim Token = authCheck.GenerateJSONWebToken("userid", accessList, )
Dim myToken As New tokenResponse
myToken.token = Token
myResponse.data = myToken
Return myResponse
So since in the above case i dont set the scope or experation its null. Is there a way to be part of the out put if null or do i need to check each value and remove it if its null
I would try the following, from vb.net when you recive the json response, add the response to a string variable the with the replace's string method try to change the null value to a new value. I hope this be useful. Thank you. :)
I am creating service account programmatically for project using java sbt play framework using google java sdk
code sample
but I'm getting this error response
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Permission iam.serviceAccountKeys.create is required to perform this operation on service account projects/from-gcloud-249112/serviceAccounts/bhavaay-anand-095#from-gcloud-249112.iam.gserviceaccount.com.",
"reason" : "forbidden"
} ],
"message" : "Permission iam.serviceAccountKeys.create is required to perform this operation on service account projects/from-gcloud-249112/serviceAccounts/bhavaay-anand-095#from-gcloud-249112.iam.gserviceaccount.com.",
"status" : "PERMISSION_DENIED"
}
What I'm doing wrong? I'm using exact code from google code sample.
public ServiceAccount createServiceAccount(String projectId, String name, String displayName) throws IOException {
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()) {
credential =
credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
}
try {
final Iam service = new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName("service-accounts")
.build();
ServiceAccount serviceAccount = new ServiceAccount();
serviceAccount.setDisplayName(displayName);
CreateServiceAccountRequest request = new CreateServiceAccountRequest();
request.setAccountId(name);
request.setServiceAccount(serviceAccount);
String serviceAccountEmail = "xxx";
ServiceAccountKey key =
service
.projects()
.serviceAccounts()
.keys()
.create(
"projects/" + projectId +"/serviceAccounts/" + serviceAccountEmail,
new CreateServiceAccountKeyRequest())
.execute();
System.out.println("Created service account: " + serviceAccount);
return serviceAccount;
} catch(GeneralSecurityException e){
System.err.println(e.getMessage());
return null;
}
}
The error is that you are missing the permission "iam.serviceAccountKeys.create" to perform that command.
i see that you are loading the default credentials:
GoogleCredential credential = GoogleCredential.getApplicationDefault();
But did you set the proper credentials before?
Try doing
gcloud auth login
or
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
See more information about it HERE.
I want to insert some row to BigQuery table throught REST API, but it fails with general exception. I don't know what is the wrong in my code. When I try to insert row with REST client from Chrome browser, it's passed.
final HttpTransport TRANSPORT = new NetHttpTransport();
final JsonFactory JSON_FACTORY = new JacksonFactory();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("foo")
.setServiceAccountScopes(Collections.singleton(BigqueryScopes.BIGQUERY))
.setServiceAccountPrivateKeyFromP12File(new File(Main.class.getClassLoader().getResource("foo").getFile()))
.build();
Bigquery service = new Bigquery.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("BigQuery Samples").build();
Bigquery.Projects.List projectListRequest = service.projects().list();
TableDataInsertAllRequest.Rows data = new TableDataInsertAllRequest.Rows();
// data.setInsertId("");
Map<String, Object> json = new HashMap<>();
json.put("from", "A");
json.put("to", "B");
TableDataInsertAllRequest.Rows row = new TableDataInsertAllRequest.Rows();
row.setJson(json);
List<TableDataInsertAllRequest.Rows> rows = new ArrayList<>();
rows.add(row);
TableDataInsertAllRequest requestData = new TableDataInsertAllRequest();
requestData.setSkipInvalidRows(true);
requestData.setIgnoreUnknownValues(true);
requestData.setKind("bigquery#tableDataInsertAllRequest");
requestData.setRows(rows);
try {
TableDataInsertAllResponse response = service.tabledata().insertAll("myDatastore "myProject", "test", requestData).execute();
System.out.println(response);
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
}
The request sent with REST client on URL https://www.googleapis.com/bigquery/v2/projects/myProject/datasets/myDatastore/tables/test/insertAll
{
"kind": "bigquery#tableDataInsertAllRequest",
"skipInvalidRows": true,
"ignoreUnknownValues": true,
"rows": [
{
"json": {
"from": "VIE",
"to": "FRA"
}
}
]
}
The exception from REST API called from Java.
com.google.api.client.googleapis.json.GoogleJsonResponseException: 503 Service Unavailable
{
"code" : 503,
"errors" : [ {
"domain" : "global",
"message" : "Error encountered during execution. Retrying may solve the problem.",
"reason" : "backendError"
} ],
"message" : "Error encountered during execution. Retrying may solve the problem."
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.Main.main(Main.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
This code is working. The problem was on server side and it was resolved after more hours automatically. Maybe it will be useful for someone.
I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}