QuickBlox create user issue (bad request) without any error message - quickblox

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;
}

Related

What should I do if the custom status code returns cors error?

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

How do you access the NFL's API's?

I've been trying to access or find away to access data from NFL.com, but have not found it yet. There is public documentation on these sites:
https://api.nfl.com/docs/identity/oauth2/index.html
but these docs do not tell you how to get a client id or client secret.
I've also tried:
http://api.fantasy.nfl.com/v2/docs
The documentation says that you need to send an email to fantasy.football#nfl.com to get the app key. I sent an email a while ago and a follow up and I've received no responses.
You can send requests to these API's and they will respond telling you that you have invalid credentials.
Have you had any success with this? Am I doing something wrong? Are these sites out of date?
EDIT: I emailed them on 10/30/2015
While I haven't had any success with api.nfl.com, I am able to get some data from the api.fantasy.nfl.com. You should have read access to all of the /players/* endpoints (e.g. http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json). I would think you need an auth token for the league endpoints and the write endpoints.
How long ago did you email them?
EDIT:
I emailed the NFL and this is what they had to say: "We've passed your API request along to our product and strategy teams. NFL.com Fantasy APIs are available on a per-use, case-by- case basis for NFL partners. Our team reviews other requests, but our APIs are typically not available for external usage otherwise."
You can replicate the experience of generating a client JWT token in Nfl.com by opening chrome inspector and going to nfl.com then clearing your application local storage and your network console, refreshing the page and then just watching the responses come across the line and how it issues a token.
I'd argue they probably have a bit of a security gap in how they issue tokens because they sent their clientId and clientSecret to the end user which is later posted back to the server create a JWT, when they should probably have some sort of end point that gens a token and also has some site origin protections, but hey makes consumption of the API a bit easier.
Usage:
using (var client = await WebClientFactory.Create())
{
foreach (var week in all)
{
var url = $"https://api.nfl.com/football/v1/games?season={year}&seasonType=REG&week={week}&withExternalIds=true";
var content = await client.DownloadStringTaskAsync(url);
var obj = JsonConvert.DeserializeObject<SeasonStripV2>(content);
// do so0mething here
}
}
The meat and potatoes:
public class WebClientFactory
{
static WebClientFactory()
{
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) =>
{
Console.WriteLine(er);
// I had some cert troubles you may need to fiddle with this if you get a 405
// if (c.Subject?.Trim() == "CN=clubsweb.san1.nfl.com")
// {
// return true;
// }
Console.WriteLine(c);
return false;
};
}
public static async Task<WebClient> Create()
{
var clientInfo = new
{
clientId = "e535c7c0-817f-4776-8990-56556f8b1928",
clientKey = "4cFUW6DmwJpzT9L7LrG3qRAcABG5s04g",
clientSecret = "CZuvCL49d9OwfGsR",
deviceId = "1259aca6-3793-4391-9dc3-2c4b4c96abc5",
useRefreshToken = false
};
var clientUploadInfo = JsonConvert.SerializeObject(clientInfo);
var webRequest = WebRequest.CreateHttp("https://api.nfl.com/identity/v1/token/client");
webRequest.Accept = "*/*";
webRequest.ContentType = "application/json";
webRequest.Method = WebRequestMethods.Http.Post;
await WriteBody(webRequest, clientUploadInfo);
var result = await GetResult(webRequest);
var tokenWrapper = JsonConvert.DeserializeObject<RootV2>(result);
var client = new WebClient();
client.Headers.Add("Authorization", $"Bearer {tokenWrapper.accessToken}");
return client;
}
private static async Task WriteBody(HttpWebRequest webRequest, string clientUploadInfo)
{
using (var stream = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(stream))
{
await sw.WriteAsync(clientUploadInfo);
}
}
}
private static async Task<string> GetResult(HttpWebRequest webRequest)
{
using (var response = await webRequest.GetResponseAsync())
{
return await GetResult((HttpWebResponse) response);
}
}
private static async Task<string> GetResult(HttpWebResponse webResponse)
{
using (var stream = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
return await sr.ReadToEndAsync();
}
}
}
private class RootV2
{
public string accessToken { get; set; }
public int expiresIn { get; set; }
public object refreshToken { get; set; }
}
}
Note you can also getting a token by calling this endpoint:
POST "https://api.nfl.com/v1/reroute"
BODY: "device_id=5cb798ec-82fc-4ba0-8055-35aad432c492&grant_type=client_credentials"
and add these headers:
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers["X-Domain-Id"] = "100";
Hooks Data provides a real-time API for major US sports including NFL.
1) Get API KEY here: https://www.hooksdata.io/signup?invite=SM4555
2) Subscribe to soccer games:
curl -H "Content-type: application/json" -d '{
"query": "SELECT * FROM NFLGames WHERE away_team.team_name = 'New England Patriots' OR home_team.team_name = 'New England Patriots' AND start_datetime.countdown = 3600"}' 'http://api.hooksdata.io/v1/subscriptions'
DOCS: https://www.hooksdata.io/docs/api/datasources/nflgames/
3) Optional: Add a Webhooks URL where you want to get the data: https://www.hooksdata.io/webhooks
4) Pull the data using fetch endpoint https://www.hooksdata.io/docs/api/api-reference/#query-datasource
5) Get all the data in JSON:
{
"matches_count": 1,
"results": [
{
"_entity_type": "NFLGame",
"_id": "NFLGame_400999173",
"away_score": null,
"away_team": {
"_entity_type": "NFLTeam",
"_id": "NFLTeam_NE",
"acronym": "NE",
"division": "AFC East",
"id": "NFLTeam_NE",
"team_name": "New England Patriots"
},
"game_id": "400999173",
"home_score": null,
"home_team": {
"_entity_type": "NFLTeam",
"_id": "NFLTeam_PHI",
"acronym": "PHI",
"division": "NFC East",
"id": "NFLTeam_PHI",
"team_name": "Philadelphia Eagles"
},
"link": "http://espn.go.com/nfl/game?gameId=400999173",
"start_datetime": null,
"status": "FUTURE"
}
]
}

azure active directory graph REST api call through SP.WebRequestInfo on SharePoint Online

Trying to make a REST call through SharePoint's SP.WebRequestInfo.
I'm getting the error "The remote server returned the following error while establishing a connection - 'Unauthorized'." trying to call https://graph.windows.net/[Client]/users?api-version=2013-11-0.
I've successfully retrieved a access token.
Can you help me out why i'm getting this error?
Here is the code i'm using:
var url = "https://graph.windows.net/xxx/users/?api-version=2013-11-08";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("GET");
request.set_headers({
"Authorization": token.token_type + " " + token.access_token,
"Content-Type": "application/json"
});
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var responseBody = JSON.parse(response.get_body());
deferred.resolve(responseBody);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
The code for retrieving the token is:
this.getToken = function (clientId, clientSecret) {
var deferred = $q.defer();
var resource = "https://graph.windows.net";
var formData = "grant_type=client_credentials&resource=" + encodeURIComponent(resource) + "&client_id=" + encodeURIComponent(clientId) + "&client_secret=" + encodeURIComponent(clientSecret);
var url = "https://login.windows.net/xxxxxx.onmicrosoft.com/oauth2/token?api-version=1.0";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("POST");
request.set_body(formData);
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var token = JSON.parse(response.get_body());
deferred.resolve(token);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
function errorHandler() {
deferred.reject(response.get_body());
}
return deferred.promise;
};
Erik, something is strange here - you are using the client credential flow from a JavaScript client - this reveals the secret issued to the client app to the user of the JS app.
The client credential flow also requires the directory admin to grant directory read permission to the client application - not sure if this was already configured - nevertheless it must only be used with a confidential client, not a public client like a JS app.
Azure AD does not yet implement the implicit_grant oauth flow using which a JS client app can acquire an access token on behalf of the user over redirect binding (in the fragment). This is a hugh-pro requirement that we're working on - stay tuned.

Google Analytics API fails to login with bad request and invalidKey

I´m trying to get some data from analytics, but can´t get authorized. It returns the following error:
I renewed my credentials at google console several times.
The code I´m using:
var clientId = '*****************0m1fnmuae00abaaq.apps.googleusercontent.com';
var apiKey = '********fB9eVMVfQ0oR6';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
gapi.client.load('analytics', 'v3', handleAuthorized);
} else {
handleUnauthorized();
}
}
function handleAuthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
authorizeButton.style.visibility = 'hidden';
runDemoButton.style.visibility = '';
runDemoButton.onclick = makeApiCall;
outputToPage('Click the Run Demo button to begin.');
}
function handleUnauthorized() {
var authorizeButton = document.getElementById('authorize-button');
var runDemoButton = document.getElementById('run-demo-button');
runDemoButton.style.visibility = 'hidden';
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
outputToPage('Please authorize this script to access Google Analytics.');
}
function handleAuthClick(event) {
gapi.auth.authorize({
client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
When I run the code, it returns the following error:
error: {errors:[{domain:usageLimits, reason:keyInvalid, message:Bad Request}], code:400, message:Bad Request}
code: 400
errors: [{domain:usageLimits, reason:keyInvalid, message:Bad Request}]
0: {domain:usageLimits, reason:keyInvalid, message:Bad Request}
domain: "usageLimits"
message: "Bad Request"
reason: "keyInvalid"
message: "Bad Request"
Someone can help with this issue?
Find the error.
In Google Console, you have to create the OAuth ID and the Public API Access ID.
Take the cliendId from the first and the APIKey from the second.
I think it´s very confuse, and it could be more explicit in documentation.

huawei api sms documentation

any one have the huawei SMS API documentation? (api/sms/sms-list)
I need to know how to talk with this API to get the SMS list:
It must be something like this:
<request>
<PageIndex>1</PageIndex>
<ReadCount>20</ReadCount>
<BoxType>1</BoxType>
<SortType>0</SortType>
<Ascending>0</Ascending>
<UnreadPreferred>0</UnreadPreferred>
</request>
But I got only a error code 100003 as answer. And I don't what that mean.
Thank You,
michel
I have done this on an Huawei E5221 with Python. The error you are getting is because you are not authenticated and need to login first. Then the list can be retrieved.
Also note that all API requests are POST's and not GET's.
Method to login:
def LoginToSMSGateway(sms_gateway_ip, username, password):
api_url = '/api/user/login'
post_data = '<request><Username>'+username+'</Username><Password>'+ base64.b64encode(password) +'</Password>'
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data)
if r.status_code == 200:
result = False
root = ET.fromstring(r.text)
for results in root.iter('response'):
if results.text == 'OK':
result = True
return result
else:
return False
Method to retrieve SMS List (The method will turn the XML results into a Python list of SMS's):
def GetSMSList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
api_url = '/api/sms/sms-list'
post_data = '<?xml version="1.0" encoding="UTF-8"?><request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = {'Referer': 'http://' + sms_gateway_ip + '/html/smsinbox.html'}
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages:
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
return resultsList
To use it(The IP and credentials are the default values and need to be secured.) :
if LoginToSMSGateway('192.168.1.1', 'admin', 'admin'):
print 'Logged in.'
smsList = GetSMSList('192.168.1.1')
for sms in smsList:
print sms.Message
Since this the subject has been posted I think the API has changed a bit.
To get the SMS list, no need to login but you do need to get a sessionID and the corresponding Token. You can use that Method to get them.
def GetTokenAndSessionID(sms_gateway_ip):
url = '/html/smsinbox.html'
r = requests.get(sms_gateway_ip + url)
Setcookie = r.headers.get('set-cookie')
sessionID = Setcookie.split(';')[0]
token = re.findall(r'"([^"]*)"', r.text)[2]
return token, sessionID
And then the Method to get the sms list (It's using the first Method to wrap the sessionID and the Token in the headers).
def GetSmsList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
url = '/api/sms/sms-list'
token,sessionID = GetTokenAndSessionID(sms_gateway_ip)
post_data = '<request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>2</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'__RequestVerificationToken': token,
'Cookie': sessionID
}
r = requests.post(sms_gateway_ip + url, data = post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages :
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
To use it you just need to call it with the ip of the sms gateway: 192.168.8.1
GetSmsList(sms_gateway_ip)
Similar Code in Java hereunder using Apache HTTP Client classes
CloseableHttpClient httpclient = HttpClients.createDefault();
// 1. Have apache HTTPClient manage the cookie containing the SessionID
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// 2. Extract the token
String token = "";
HttpGet hget = new HttpGet("http://192.168.8.1/html/smsinbox.html");
CloseableHttpResponse getRespo = httpclient.execute(hget, httpContext);
try {
StatusLine statusLine = getRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = getRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Get response contains no content");
}
long len = entity.getContentLength();
StringTokenizer st = null;
if (len != -1 && len > 250) {
st = new StringTokenizer(EntityUtils.toString(entity).substring(0, 250), "\"");
}
int i = 1;
while (st != null && st.hasMoreTokens()) {
if (i++ == 10) {
token = st.nextToken();
break;
} else {
st.nextToken();
}
}
} finally {
getRespo.close();
}
System.out.println("Token: " + token);
// 3. Get the SMS messages using the Token
HttpPost hpost = new HttpPost("http://192.168.8.1/api/sms/sms-list");
String xmlRequest = "<request><PageIndex>1</PageIndex><ReadCount>1</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>1</UnreadPreferred></request>";
StringEntity reqEntity = new StringEntity(xmlRequest);
reqEntity.setContentType("text/xml");
hpost.setEntity(reqEntity);
hpost.addHeader("__RequestVerificationToken", token);
CloseableHttpResponse postRespo = httpclient.execute(hpost, httpContext);
try {
StatusLine statusLine = postRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = postRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
System.out.println(EntityUtils.toString(entity));
//Your further processing here.
} finally {
postRespo.close();
}