OneNote API - Cannot get Pages - c#

I have been playing around with the OneNote API, and have been successful at getting Notebooks,Sections,Pages.
Today however I have been unsuccessful getting the pages using the Section.pagesUrl.
My Request: https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!19161/pages
Where 0-2B36C9469D6FE2E!19161 is the ID of the section.
This has worked before, but has somehow stopped working.
Right before this request I successfully get the Notebooks, then once finding correct notebook from the returned list, get the sections and again find the correct section.
The response I am getting is 200(OK) but an empty array:
{
"#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/sections('0-2B36C9469D6FE2E%2119161')/pages",
"value":[
]
}
Although I can see the same Notbooks and Sections in my OneNote client. And sections do have pages. But I am not getting them any more.
Any reason why this could be happening?
Could it be a bug on your side or is there something I'm missing?
I add the Bearer token to the HttpClient like so:
_client = new HttpClient();
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenService.AccessToken);
Which seemed to work last week, and it is still working for getting Notebooks/Sections
EDIT: Requests + Responses
Request that works (getting sections):
GET https://www.onenote.com/api/v1.0/notebooks/0-2B36C9469D6FE2E!19159/sections HTTP/1.1
Authorization: Bearer EwB4Aq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAV1uu7Y2xsmzQFS/JyikQRMlK3+hurlsMQZTiYaefQ5ZVjZnnsB5bAeXFSUAGmNw4/B7DBk/tbjwWw5WzBFv0wdJERyLqCXU42WfpDKuHeZXZVS1p14teY0dr7OzN+G10Fn3/grWeHiRISlAqCBh6vV+qEO+11kFhxiCjERey6BJrMJVMCzMundN59uDM/jj8jJ9T7q2LlMqZQXFYra+DfrxWGCPzNMaJMRQYDpwrmov3kZlx2ZfL+k8Hv7luK7euEztfj5iTD4sJBCC2dURdysJdI//R0YRf5do94MyP2FD9dsLwhbl9qEhuJ+nxfVCja+s3d+GXggOBr29ivzbLYQDZgAACIabXCL9fNi6SAHeSujyYzD8QQdsytnb8nc2noza9JEWKr/tGHn2G/SofZBYrMEZCx5PBAKWghhWY40z2TCnD6MRgyFSBoqbGimNOkb7/vMHPgBUKJrxIgCgJmbW15IuYkZ11j7CK5+/JYyk+ufIjA8VEdl+HjDaUi35Hd9n8919XpQmHSH9aIZc8reC/7L90b5flE01i/ngXjuntxH92MKPm92+WVDuN9d4QWez6YEYpsBgynpx6BP8PfNbhu1E1LZUa9ZnwdBA1Pw0oYvC8jvfhx8bDhnZc2YMEQo/0XZSx5WUdVbBQfmU8gbQD86Ms3hm6fSVXxzzHIvMy0WR5Wpqr4A3+amUNFp6EApcCRI0Ydf+VLmiHHNcKWHGRaSUFDRsmaSlmmrQiBATtG4wJihywrkePrT4OBaJD/jVH9FvIZrLa33POSN1CLcFXlbKezyAYwE=
Accept: application/json
Host: www.onenote.com
Response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; odata.metadata=minimal
Expires: -1
Server: Microsoft-IIS/8.5
X-CorrelationId: d3c85fde-c8e0-4e4e-a4df-87a3f57f146e
X-UserSessionId: d3c85fde-c8e0-4e4e-a4df-87a3f57f146e
X-OfficeFE: OneNoteServiceFrontEnd_IN_0
X-OfficeVersion: 16.0.6023.1561
X-OfficeCluster: neu-www.onenote.com
P3P: CP="CAO DSP COR ADMa DEV CONi TELi CUR PSA PSD TAI IVDi OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR"
X-Content-Type-Options: nosniff
Request-Processing-Time: 828.1859 ms
OData-Version: 4.0
Preference-Applied: odata.include-annotations=*
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 25 Jul 2015 12:10:58 GMT
Content-Length: 3135
{
"#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections(parentNotebook(id,name,self),parentSectionGroup(id,name,self))","value":[
{
"isDefault":false,"pagesUrl":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!41276/pages","name":"Agily","createdBy":"LnDSoft Test","lastModifiedBy":"LnDSoft Test","lastModifiedTime":"2015-07-23T11:39:46.9Z","id":"0-2B36C9469D6FE2E!41276","self":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!41276","createdTime":"2015-07-15T23:39:22.44Z","parentNotebook#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2141276')/parentNotebook(id,name,self)/$entity","parentNotebook":{
"id":"0-2B36C9469D6FE2E!19159","name":"Agily","self":"https://www.onenote.com/api/v1.0/notebooks/0-2B36C9469D6FE2E!19159"
},"parentSectionGroup#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2141276')/parentSectionGroup(id,name,self)/$entity","parentSectionGroup":null
},{
"isDefault":false,"pagesUrl":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!19161/pages","name":"AgilyTest","createdBy":"LnDSoft Test","lastModifiedBy":"M C","lastModifiedTime":"2015-07-21T23:16:18.85Z","id":"0-2B36C9469D6FE2E!19161","self":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!19161","createdTime":"2015-01-04T23:50:32.41Z","parentNotebook#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2119161')/parentNotebook(id,name,self)/$entity","parentNotebook":{
"id":"0-2B36C9469D6FE2E!19159","name":"Agily","self":"https://www.onenote.com/api/v1.0/notebooks/0-2B36C9469D6FE2E!19159"
},"parentSectionGroup#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2119161')/parentSectionGroup(id,name,self)/$entity","parentSectionGroup":null
},{
"isDefault":false,"pagesUrl":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!41275/pages","name":"OtherSection","createdBy":"LnDSoft Test","lastModifiedBy":"LnDSoft Test","lastModifiedTime":"2015-07-15T23:36:15.037Z","id":"0-2B36C9469D6FE2E!41275","self":"https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!41275","createdTime":"2015-07-15T23:35:13.9Z","parentNotebook#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2141275')/parentNotebook(id,name,self)/$entity","parentNotebook":{
"id":"0-2B36C9469D6FE2E!19159","name":"Agily","self":"https://www.onenote.com/api/v1.0/notebooks/0-2B36C9469D6FE2E!19159"
},"parentSectionGroup#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks('0-2B36C9469D6FE2E%2119159')/sections('0-2B36C9469D6FE2E%2141275')/parentSectionGroup(id,name,self)/$entity","parentSectionGroup":null
}
]
}
Request that does not work (getting pages, using the URL from above):
Request:
GET https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!19161/pages HTTP/1.1
Authorization: Bearer EwB4Aq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAV1uu7Y2xsmzQFS/JyikQRMlK3+hurlsMQZTiYaefQ5ZVjZnnsB5bAeXFSUAGmNw4/B7DBk/tbjwWw5WzBFv0wdJERyLqCXU42WfpDKuHeZXZVS1p14teY0dr7OzN+G10Fn3/grWeHiRISlAqCBh6vV+qEO+11kFhxiCjERey6BJrMJVMCzMundN59uDM/jj8jJ9T7q2LlMqZQXFYra+DfrxWGCPzNMaJMRQYDpwrmov3kZlx2ZfL+k8Hv7luK7euEztfj5iTD4sJBCC2dURdysJdI//R0YRf5do94MyP2FD9dsLwhbl9qEhuJ+nxfVCja+s3d+GXggOBr29ivzbLYQDZgAACIabXCL9fNi6SAHeSujyYzD8QQdsytnb8nc2noza9JEWKr/tGHn2G/SofZBYrMEZCx5PBAKWghhWY40z2TCnD6MRgyFSBoqbGimNOkb7/vMHPgBUKJrxIgCgJmbW15IuYkZ11j7CK5+/JYyk+ufIjA8VEdl+HjDaUi35Hd9n8919XpQmHSH9aIZc8reC/7L90b5flE01i/ngXjuntxH92MKPm92+WVDuN9d4QWez6YEYpsBgynpx6BP8PfNbhu1E1LZUa9ZnwdBA1Pw0oYvC8jvfhx8bDhnZc2YMEQo/0XZSx5WUdVbBQfmU8gbQD86Ms3hm6fSVXxzzHIvMy0WR5Wpqr4A3+amUNFp6EApcCRI0Ydf+VLmiHHNcKWHGRaSUFDRsmaSlmmrQiBATtG4wJihywrkePrT4OBaJD/jVH9FvIZrLa33POSN1CLcFXlbKezyAYwE=
Accept: application/json
Host: www.onenote.com
Response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; odata.metadata=minimal
Expires: -1
Server: Microsoft-IIS/8.5
X-CorrelationId: fe872c95-f8af-41e3-b019-4e6504a5e8df
X-UserSessionId: fe872c95-f8af-41e3-b019-4e6504a5e8df
X-OfficeFE: OneNoteServiceFrontEnd_IN_0
X-OfficeVersion: 16.0.6023.1561
X-OfficeCluster: neu-www.onenote.com
P3P: CP="CAO DSP COR ADMa DEV CONi TELi CUR PSA PSD TAI IVDi OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR"
X-Content-Type-Options: nosniff
Request-Processing-Time: 703.1688 ms
OData-Version: 4.0
Preference-Applied: odata.include-annotations=*
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 25 Jul 2015 12:10:58 GMT
Content-Length: 143
{
"#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/sections('0-2B36C9469D6FE2E%2119161')/pages","value":[
]
}
EDIT 2: Still not working
Request:
GET https://www.onenote.com/api/v1.0/sections/0-2B36C9469D6FE2E!19161/pages HTTP/1.1
Authorization: Bearer EwCAAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAZdDnoj6ATyof3wJ8jfSPNcSx+uxW4fVURSJ29iChWlIuhitDH11wKItykmBolKwHRyINjz4+dknXJcNfHgGv6R7AOpSeuNt/lr+h/9HUS20/aV0/NssaoXh7lyGKQekX22D+KtcprNi9zoXbtR6t07tz7aHyx3V7F4qHQVZmG2psWTGVpwa/TTCLB4jgDCEHwQYV9XgjGnpIJgyIZvmI+hZ0DRkBF9gyp49BMNrgdi75jLyfecbYU1MaxBdaUQuhZFXjGEv8pMecsscGcLM9JvbtT6Ap6k6mQv5D6GeCe/CHxgQO+3IoXXRLG/n61eGHpf8/WbQorzeCDnbbtcSkCYDZgAACPGa/3ibM+sXUAHc/d8IiDQnNRQHYfY/sl7b179y4gRsnP5YUN7dI7CkNkFR4sSWo1Db9tBmZN3bA4LN94D4GEzDhegNrjXtm5NFrrhrGOInZzFxtlfRVa1GvgPgPc2s8clOacwE5zi2jr1SSf39AfJjBYfMK2ePYN8XRdzjBMfAXZFHv0MOIk3pAbE/Tk0YSPqRk1whxHrLFxkYvk5PI8IoWsyKIUudp7B2GwvWAE2WycX2P49yJs4qZ/+Ocu/k0jJv16kUa/szN4G8lmcEZykiKrLgGFxZbfKn8L9/sECD7Wj5X0pxH4aDnvUrcjsFNrreanAeG+KyLsHdhOL3UIy/uiLRsarLsdXmlUV2JGHdGiAdZ53wR+xKOYq7xoBP7myhxIoFoqnm7wVnKi8+2CiA8T9y+JtVToQMxjTD1xacuuZ8malpifqTTHYYXmggOaukHOcsV0TQz4JjAQ==
Accept: application/json
Host: www.onenote.com
Response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; odata.metadata=minimal
Expires: -1
Server: Microsoft-IIS/8.5
X-CorrelationId: 7cb781ec-36d4-4485-b6c1-a48f7e536298
X-UserSessionId: 7cb781ec-36d4-4485-b6c1-a48f7e536298
X-OfficeFE: OneNoteServiceFrontEnd_IN_5
X-OfficeVersion: 16.0.6023.1561
X-OfficeCluster: neu-www.onenote.com
P3P: CP="CAO DSP COR ADMa DEV CONi TELi CUR PSA PSD TAI IVDi OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR"
X-Content-Type-Options: nosniff
Request-Processing-Time: 671.9287 ms
OData-Version: 4.0
Preference-Applied: odata.include-annotations=*
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 28 Jul 2015 02:21:40 GMT
Content-Length: 143
{
"#odata.context":"https://www.onenote.com/api/v1.0/$metadata#me/notes/sections('0-2B36C9469D6FE2E%2119161')/pages","value":[
]
}
You can see in the below screenshot that pages exist
for Agily (Notebook) -> Agily (Section)

I have been investigating this issue for you today. I was wondering if you could try this request again?
Our storage layer experienced some failures over the weekend that could possibly explain the issue so I wanted to verify with you that you are seeing the issue still.
As far as I can tell from the request that you posted and the logs on our end, there is nothing wrong syntactically with the request and no obvious logic errors on our end, so the investigation is currently pointing at the storage layer as possibly being the culprit.
Thanks,
Daniel

Related

.NET 6 Web API - Not getting uniform error response for Authorization using Swagger in Mozilla, Chrome, Edge

I am using Windows authentication to validate a user trying to consume my .NET 6 Web API,
This is in Chrome,
Response headers look like,
cache-control: no-cache,no-store
content-type: application/json; charset=utf-8
date: Tue,18 Oct 2022 05:21:32 GMT
expires: -1
pragma: no-cache
server: Kestrel
transfer-encoding: chunked
however on Mozilla, I get,
In Edge, incognito, I get HTML in the Response,
And Response header looks like,
content-length: 1293
content-type: text/html
date: Mon,17 Oct 2022 22:36:10 GMT
server: Microsoft-IIS/10.0
www-authenticate: Negotiate,NTLM
x-powered-by: ASP.NET
Why am I getting such a different behavior?
I have standard error response, like displayed in the first image,
{
"statusCode": 401,
"message": "Some user not found.",
"errorCode": "USER_NOT_FOUND",
"target": "MoveNext",
"innerError": " some error"
I want this uniform response object everytime.
Tried using this IAuthorizationFilter, but still while trying from Mozilla, that breakpoint doesn't hit,
public class ControllerFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//int? currentUserId = context.HttpContext.Session.GetInt32("UserId");
var name = context.HttpContext.User.Identity.Name;
}
}
What can be done to get the uniform authorization response at all times?

Getting Microsoft.Identity (former AzureAD) to work with Swagger

I have an ASP.Net 5 Web API which is secured using The Microsoft.identity.Web package, so it is backed by Azure Active Directory.
The authentication in the API itself is working fine and without any problems.
I'm struggling when I want to get the authorization to work inside Swagger UI.
I'm using the Authorization code flow and everything seems fine at first (I get to the Microsoft login screen, can enter my credentials and receive an authorization code).
However after Swagger UI got the authorization code, it calls the token endpoint at https://login.microsoftonline.com/organizations/oauth2/v2.0/token.
The response from that call is 99% percent fine, except that it is missing the Allow-Origin-Header so the response is blocked by the browser itself and cannot reach the Swagger UI JavaScript which would then set the token it received from that response.
What am I missing here to get that header in the response?
This is the code in my Startup.cs
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("msid", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Type = Microsoft.OpenApi.Models.SecuritySchemeType.OAuth2,
Flows = new Microsoft.OpenApi.Models.OpenApiOAuthFlows
{
AuthorizationCode = new Microsoft.OpenApi.Models.OpenApiOAuthFlow
{
AuthorizationUrl = new System.Uri("https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize"),
TokenUrl = new System.Uri("https://login.microsoftonline.com/organizations/oauth2/v2.0/token"),
Scopes = new Dictionary<string, string>
{
{ "api://myClientId/access", "access" }
}
}
}
});
c.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference {Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "msid" }
},
new [] { "api://myClientId/access" }
}
});
});
This is the request which is sent from Swagger UI to https://login.microsoftonline.com/organizations/oauth2/v2.0/token
POST https://login.microsoftonline.com/organizations/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Connection: keep-alive
Content-Length: 1086
Pragma: no-cache
Cache-Control: no-cache
sec-ch-ua: "Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
X-Requested-With: XMLHttpRequest
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4585.0 Safari/537.36 Edg/94.0.972.0
sec-ch-ua-platform: "Windows"
Origin: https://localhost:5003
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://localhost:5003/
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en;q=0.8,en-US;q=0.7
grant_type=authorization_code&code=hereIsMyLongAuthorizationCode&redirect_uri=https%3A%2F%2Flocalhost%3A5003%2Fswagger%2Foauth2-redirect.html
This is the response
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
x-ms-request-id: 683dc687-7211-400b-ab02-bccdc6e9ba00
x-ms-ests-server: 2.1.11898.12 - WEULR1 ProdSlices
report-to: {"group":"network-errors","max_age":86400,"endpoints":[{"url":"https://identity.nel.measure.office.net/api/report?catId=GW+estsfd+dub2"}]}
nel: {"report_to":"network-errors","max_age":86400,"success_fraction":0.001,"failure_fraction":1.0}
Set-Cookie: fpc=...; expires=Fri, 03-Sep-2021 13:57:11 GMT; path=/; secure; HttpOnly; SameSite=None
Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly
Set-Cookie: stsservicecookie=estsfd; path=/; secure; samesite=none; httponly
Referrer-Policy: strict-origin-when-cross-origin
Date: Wed, 04 Aug 2021 13:57:10 GMT
Content-Length: 1763
{"token_type":"Bearer","scope":"api://myClientId/access","expires_in":3599,"ext_expires_in":3599,"access_token":"theToken"}
The problem was that I was using the AuthorizationCode-Flow which is only suitable for backend applications, because the client secret needs to be transmitted there.
The correct way was to use the Implicit-Flow while keeping everything else the same. That flow is intended for JS applications where it is impossible to securely send a client secret without the user being able to see it.

I get a Bad request Status Code 400 when I am trying to consume a REST API online using C#

I am working with REST APIs and trying to connect to a REST API online that I can get to fine via the browser but when I try with some simple code, it is failing:
var client = new HttpClient();
var uri = new Uri("http://dummy.restapiexample.com/api/v1/employee/1");
try
{
var response = client.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine($"{response.StatusCode} - {response.ToString()}");
}
}
catch (Exception ex)
{
Console.WriteLine(#"\tERROR {0}", ex.Message);
}
The response message I get is the following:
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Type, X-Requested-With, X-authentication, X-client
Host-Header: c2hhcmVkLmJsdWVob3N0LmNvbQ==
Pragma: no-cache
Referrer-Policy:
Response: 400
Cache-Control: no-cache
Date: Fri, 10 Apr 2020 10:38:39 GMT
Set-Cookie: PHPSESSID=a8474e93077d190fe6bcdcb1ae1cbd42; path=/
Set-Cookie: ezoadgid_133674=-1; Path=/; Domain=restapiexample.com; Expires=Fri, 10 Apr 2020 11:08:39 UTC
Set-Cookie: ezoref_133674=; Path=/; Domain=restapiexample.com; Expires=Fri, 10 Apr 2020 12:38:39 UTC
Set-Cookie: ezoab_133674=mod58-c; Path=/; Domain=restapiexample.com; Expires=Fri, 10 Apr 2020 12:38:39 UTC
Set-Cookie: active_template::133674=pub_site.1586515119; Path=/; Domain=restapiexample.com; Expires=Sun, 12 Apr 2020 10:38:39 UTC
Server: nginx/1.16.0
Vary: Accept-Encoding
Vary: Accept-Encoding
Vary: User-Agent
Vary: X-APP-JSON
X-Ezoic-Cdn: Miss
X-Middleton-Response: 400
X-Sol: pub_site
Content-Length: 75
Content-Type: application/json; charset=utf-8
Expires: Thu, 19 Nov 1981 08:52:00 GMT
}
Can someone point me in the right direction as to how I can fix this?
The problem appears to be with the REST API itself, because when I used the following REST API https://jsonplaceholder.typicode.com/todos/1 it worked fine.

Google Drive: Error in retrieving access and refresh tokens

I am trying to access google drive from my app for WP7. But when i try to get access token in exchange for Authorization code, I get BAD REQUEST from server.
My POST request as seen in Fidler:
POST https://accounts.google.com/o/oauth2/token HTTP/1.1
Accept: */*
Referer: file:///Applications/Install/7128457C-3AF4-41C4-A606-742068B1463F/Install/
Content-Length: 240
Accept-Encoding: identity
Content-Type: application/x-www-form-urlencoded
User-Agent: NativeHost
Host: accounts.google.com
Connection: Keep-Alive
Cache-Control: no-cache
code=<*Authorization_Code*>&
client_id=<*My_Client_Id*>&
client_secret=<*My_Client_Secret*>&
redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&
grant_type=authorization_code
Response from server:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Sat, 07 Sep 2013 14:05:35 GMT
Content-Type: application/json
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic
Transfer-Encoding: chunked
21
{
"error" : "invalid_request"
}
0
My Code:
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "code", HttpUtility.UrlEncode(AuthorizationCode));
postData.AppendFormat("&\n{0}={1}", "client_id", HttpUtility.UrlEncode(ClientId));
postData.AppendFormat("&\n{0}={1}", "client_secret", HttpUtility.UrlEncode(ClientSecret));
postData.AppendFormat("&\n{0}={1}", "redirect_uri", HttpUtility.UrlEncode("urn:ietf:wg:oauth:2.0:oob"));
postData.AppendFormat("&\n{0}={1}", "grant_type", HttpUtility.UrlEncode("authorization_code"));
WebClient client = new WebClient();
client.UploadStringCompleted += TokenResponse;
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.UploadStringAsync(new Uri("https://accounts.google.com/o/oauth2/token",UriKind.Absolute), "POST", postData.ToString());
I get this result both on emulator as well as Lumia 820. I also tried without using HttpUtility in POST request but didn't work. Any help?
Its likely due to the fact that you are adding a new line via \n between all the param/value pairs.
I do it without that without it and it works - https://github.com/entaq/GoogleAppsScript/blob/master/IO2013/YouTubeAnalytics/oauth2.gs#L25

Acquire Twitter request token failed

I followed the instruction at http://dev.twitter.com/pages/auth#request-token, and developed a c# class to do the OAuth authorization. I used the parameters on the page, and the output signature base string and signature match that on the page. So I think the algorithm part is correct. Then I replaced the parameters with the ones in my twitter application, but I failed to acquire the request token from Twitter service. And the response data is "Failed to validate oauth signature and token".
Here's the request I send (I used http, instead of https for debug):
POST http://api.twitter.com/oauth/request_token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: OAuth oauth_callback="http%3A%2F%2Flocalhost%3A3005%2Fthe_dance%2Fprocess_callback%3Fservice_provider_id%3D11", oauth_consumer_key="GDdmIQH6jhtmLUypg82g", oauth_nonce="QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1272323042", oauth_version="1.0", oauth_signagure="IP%2FEEoc4tKdiobM%2FKH5cPK69cJM%3D"
Host: api.twitter.com
Proxy-Connection: Keep-Alive
And here's the response:
HTTP/1.1 401 Unauthorized
Connection: Keep-Alive
Connection: Proxy-Support
Content-Length: 44
Via: 1.1 APS-PRXY-09
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Date: Fri, 08 Apr 2011 05:47:20 GMT
Content-Type: text/html; charset=utf-8
Server: hi
Proxy-Support: Session-Based-Authentication
Status: 401 Unauthorized
X-Transaction: 1302241640-40339-46793
Last-Modified: Fri, 08 Apr 2011 05:47:20 GMT
X-Runtime: 0.01519
Pragma: no-cache
X-Revision: DEV
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Set-Cookie: k=207.46.55.29.1302241640766556; path=/; expires=Fri, 15-Apr-11 05:47:20 GMT; domain=.twitter.com
Set-Cookie: guest_id=13022416407746962; path=/; expires=Sun, 08 May 2011 05:47:20 GMT
Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCEiBpjMvAToHaWQiJWMzMTViOGZiNDkzMDRi%250ANjNhMmQwYmVkZDBhNTc2NTc4IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--177afd5c0f6fe30005ab9a9412e6f85ab03cbfa7; domain=.twitter.com; path=/; HttpOnly
Vary: Accept-Encoding
Failed to validate oauth signature and token
This is how I generate the normalized parameters:
string.Join("&", (from d in this.BuildParameterDict()
select string.Format("{0}={1}", OAuthEncoding.Encode(d.Key), OAuthEncoding.Encode(d.Value))))
The BuildParameterDict method will sorted build a list with: parameters from query string; parameters from body; parameters sepcific to 'oauth', except the 'oauth_signature'.
Then the signature base string is generated by:
StringBuilder sb = new StringBuilder();
sb.Append(OAuthEncoding.Encode(this._request.Method));
sb.Append('&');
sb.Append(OAuthEncoding.Encode(this.GetNormalUri()));
sb.Append('&');
sb.Append(OAuthEncoding.Encode(this.GetNormalParameters()));
This is the generated base string with parameters from the above page:
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%253A3005%252Fthe_dance%252Fprocess_callback%253Fservice_provider_id%253D11%26oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DQP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323042%26oauth_version%3D1.0
which is identical to the string on that page.
Your oauth signature is listed as "oauth_signagure" in your request.
oAuth parameters has to be sorted before sending, but signature has to be at the end of the authorization request.(9.1.1 in http://oauth.net/core/1.0/#anchor14)
You may also need to specify a realm="/oauth/request_token". It's optional, but as I remember correctly Twitter wants this one for a request token.
If you can add your code we might find what's going on, as you might not be building your request and key for signature hashing correctly.

Categories