oauth version 1 missing authentication credentials - oauth

When I try to execute OAuth v1 request I got
"Response{code=401, message='Unauthorized', body='null', headers={Keep-Alive=timeout=60, Transfer-Encoding=chunked, null=HTTP/1.1 401 Unauthorized, Server=CodeBig, WWW-Authenticate=OAuth realm="classified.net", Connection=keep-alive, CodeBig-Error-Message=missing authentication credentials, Date=Sun, 16 Oct 2016 08:16:16 GMT, Via=1.1 CodeBig, Content-Type=text/plain}}"###
Here is a code snippet of using scribejava
String apiKey = "fsfsfsf";
String apiSecret = "fsfsfsfsf";
String PROTECTED_RESOURCE_URL = "https://somerealm.net/";
OAuth10aService service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret).signatureType(SignatureType.QueryString).build(new MyAOuthv1());
OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URL, service);
request.addOAuthParameter(OAuthConstants.TIMESTAMP, service.getApi().getTimestampService().getTimestampInSeconds());
request.addOAuthParameter(OAuthConstants.NONCE, service.getApi().getTimestampService().getNonce());
request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "blahblahblah");
request.addOAuthParameter(OAuthConstants.CONSUMER_SECRET, "blahblahblah");
request.addOAuthParameter(OAuthConstants.SIGN_METHOD, service.getApi().getSignatureService().getSignatureMethod());
request.addOAuthParameter(OAuthConstants.VERSION, "1.0");
request.addOAuthParameter(OAuthConstants.SIGNATURE, getSignature(service, request));
request.addPayload("{\"id\":12345,\"message\":\"some text\"}");
request.addHeader("Content-Type", "application/json");
Response response = request.send();
However If I use firefox's REST Client I get it working.
What is wrong? OAuth vesrion is 1.0

Why don't you use OAuth10aService::signRequest method?

Related

Twitch API OAuth

Please let me know if this is not possible...but in an effort to refactor my personal API I decided to start calling the Twitch endpoints through my API so data can be combined. To do this I direct the user to the auth page and get a bearer token back. I then pass that token to my API in the header. For some reason I get a 401 if I try to use that token at all from my API. I have no idea why as I can't view a reason in the response. The token works from postman.
Here is an example of a request I make in my API:
public async Task<bool> ValidateToken()
{
var response = await client.GetAsync("https://id.twitch.tv/oauth2/validate");
return response.StatusCode == HttpStatusCode.OK;
}
The HttpClient is created as follows before the validation method is called:
public TwitchService(IHeaderDictionary headers)
{
StringValues token;
StringValues clientId;
var hasToken = headers.TryGetValue("Authorization", out token);
var hasClientId = headers.TryGetValue("Client-id", out clientId);
client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
if (hasToken)
{
var authToken = token.ToString().Replace("Bearer", "");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
}
if (hasClientId)
{
client.DefaultRequestHeaders.Add("Client-ID", clientId.ToString());
}
}
It turns out that the auth header is removed by the HttpClient and this is by design. The following link gives a good explanation about it: Authorization header is lost on redirect

web api 2 - Oauth2 Bearer token access is forbidden

I have an mvc 5 application with an web api 2. (.NET 4.6)
I implemented the oauth2 configuration next to the authentication for my mvc app (app.UseCookieAuthentication) :
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
Provider = new AspNetIdentityOAuthAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1000),
};
app.UseOAuthBearerTokens(OAuthServerOptions);
My apis are protected with the Authorize Attribute (global filter).
I use the client credentials grant
I followed these two articles (that are the same)
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
https://mitchelsellers.com/blogs/2017/05/10/adding-webapi-oauth-authentication-to-an-existing-project
I'm able to get a token for my user, but when I want to use the token to access my Api, I get a 403 forbidden error
HttpClient client = new HttpClient();
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "client_credentials");
parameters.Add("client_id", "4rclFahG7gho8erzbsmTbw==");
parameters.Add("client_secret", "IBSqiYb0kT/lzV0gpQsPxkUDI9ztu0dhHWDe4VQDzKGYm2pl+75sMVfEsoGo4FAxFm0qZUFcDrVMrfqYhn2bzw==");
var content = new FormUrlEncodedContent(parameters);
try
{
HttpResponseMessage result = client.PostAsync("http://localhost:49594/oauth/token", content).Result;
string jsonResult = result.Content.ReadAsStringAsync().Result;
var resultObject = JsonConvert.DeserializeObject<TokenResult>(jsonResult);
var accessToken = resultObject.access_token;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
result = client.GetAsync("http://localhost:49594/api/v1/echo?id=myt
estvalue").Result;
// RESULT is 403 - Forbidden
I tested with postman as well, and the result is the same.
did anyone experienced the same problem ?
do you know what I' missing ?
Update :
It's working if I deploy my application on a server (azure app services) but still not on my machine
I found the reason of my issue !
I'm using stuntman (https://rimdev.io/stuntman/) for my dev and I forgot to configure it for oauth ...
This line was missing :
StuntmanOptions.AllowBearerTokenPassthrough = true;

QuickBooks Authentication error when getting basic company information

I'm writing a simple desktop application to get information from QuickBooks(developer account using demo account(UK) data) and in this regard I've been able to go past the OAuth flow. However, I've not been able to get the basic company information
The below is a capture of the Fiddler request and response:
GET https://quickbooks.api.intuit.com/v3/company/123145829830639/companyInfo/123145829830639 HTTP/1.1
Authorization: oauth_token="****", oauth_nonce="z4x0a196", oauth_consumer_key="****", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1499283607", oauth_version="1.0", oauth_signature="EGw6Ty%2BKFAawrH1%2FSxQuFwaMcEo%3D"
Content-Type: application/json
Host: quickbooks.api.intuit.com
The generation of the header is similar to https://developer.intuit.com/v2/apiexplorer?apiname=V3QBO#?id=CompanyInfo but I end up getting the following response(Fiddler partial response) based on the request
intuit_tid: gw-c4e19f89-df78-42a5-ae7e-216187421143
Set-Cookie: JSESSIONID=21BF1FFEE48B39538E82485FD25C4280.c51-pprdsbxas901; Path=/; Secure; HttpOnly
QBO-Version: 1706.912
ErrorCode: 100
ErrorCause: AuthenticationErrorGeneral: SRV-110-Authentication Failure , statusCode: 401
Message: General Authentication Error
The code to access company information is as below:
string companyInfo = String.Format("company/{0}/companyInfo/{0}", authenticator.OAuthProfile.realmId);
string ciUrl = BASE_URL + companyInfo; //https://quickbooks.api.intuit.com/v3/
var sb = new System.Text.StringBuilder();
sb.AppendFormat("oauth_token=\"{0}\", oauth_nonce=\"{1}\", oauth_consumer_key=\"{2}\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"{3}\", oauth_version=\"1.0\", oauth_signature=\"{4}\"",
Manager.UrlEncode(_token),
Manager.UrlEncode(_nonce),
Manager.UrlEncode(_consumer_key),
Manager.UrlEncode(_timestamp),
Manager.UrlEncode(_signature));
var authorisationHeader = sb.ToString().TrimEnd(' ').TrimEnd(',');
// Request Company Information
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ciUrl);
request.Headers.Add("Authorization", authorisationHeader);
request.Method = "GET";
request.ContentType = "application/json";
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
// get 401
}
Used sandbox URL and added minorversion to the base URL
I attempted setting BASE_URL set to the sandbox url(https://sandbox-quickbooks.api.intuit.com/v3) and also set minorversion to be 4.
Any help is much appreciated.
Hopefully this helps, but here is a Java snippet using their SDK that works for me:
OAuthAuthorizer oauth = new OAuthAuthorizer(System.env.QB_OAUTH_CONSUMER_KEY, System.env.QB_OAUTH_CONSUMER_SECRET,
vendor.intuitOAuthAccessToken, vendor.intuitOAuthAccessSecret);
UUID trackingID = UUID.randomUUID()
log.info("About to init Context companyID=" + vendor.realmId + ", app_token=" + System.env.QB_APP_TOKEN + ", uuid=" + trackingID.toString())
Context context = new Context(oauth, System.env.QB_APP_TOKEN, ServiceType.QBO, vendor.realmId)
context.setMinorVersion("4")
context.setTrackingID(trackingID)
log.info("About to set BaseURL")
Config.setProperty(Config.BASE_URL_QBO, System.env.QB_BASE_URL + "/v3/company");
log.info("About to init DataService")
// get all customers
log.info("About to executeQuery")
DataService service = new DataService(context)
QueryResult queryResult = service.executeQuery("select * from customer");
In my case, QB_BASE_URL=https://sandbox-quickbooks.api.intuit.com
*NOTE there isn't a trailing slash
vendor.intuitOAuthAccessToken and vendor.intuitOAuthAccessSecret are the values you get back after the oauth flow

IdentityServer3 Response status code does not indicate success: 400 (Bad Request)

I always get Bad Request 400 from IdentityServer3. I am trying for 3 days now but no luck :( Anyone could please tell me what am I doing wrong?
I am trying to access IdentityServer3 hosted by another vendor that I have no control. The vendor has asked us to implement Implement OAuth2 authentication with Bearer token. The vendor provided us with the Client ID, Client Secret and the URL to be used is http://www.xxxxxx.com/identity/connect/token
The vendor told us to use to request bearer token and use it in the request headers Authorization: Bearer
I can successfully obtain the bearer token from vendor. But when I call the
GET /api/profiles/myemailaddress#gmail.com I get Bad Request 400
Here is what I have done:
TokenClient client = new TokenClient("http://www.xxxxxx.com/identity/connect/token", "myclientid", "myclientsecret", AuthenticationStyle.PostValues);
var response = await client.RequestResourceOwnerPasswordAsync("myemailaddress#gmail.com", "mypassword", "profile"); // successfully gives me the token
i got the access token, now i want to use the token to request user profile:
var clienthttp = new HttpClient();
clienthttp.BaseAddress = new Uri("http://www.xxxxxx.com");
clienthttp.SetBearerToken(response.AccessToken);
var json = await clienthttp.GetStringAsync("http://www.xxxxxx.com/api/profiles/myemailaddress#gmail.com"); // error Bad Request 400
Additional Info:
"scopes_supported":["profile","offline_access"],
"claims_supported":[]
Thank you.
The vendor was expecting additional value in the header. Since my request was missing that additional value, they returned Bad Request. I had to modify my code to find the exact reason of bad request.
Here is the updated code, might be useful for someone:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.xxxxx.com");
client.SetBearerToken(response.AccessToken);
var callApiResponse = client.GetAsync("api/profiles/myemailaddress#gmail.com").Result;
string tokenresponse = callApiResponse.StatusCode.ToString();
string clientresult = callApiResponse.Content.ReadAsStringAsync().Result;
tokenresponse: "Bad Request 400"
clientresult: "Missing CompanyID in the header"
Then I knew that they also expect companyid in the header so I added it. then all was good.
client.DefaultRequestHeaders.Add("CompID", "xxxxxx");
I had a similar error (Response status code does not indicate success: 400 (Bad Request)) for different resource not identity server. i manage to resolve that using FormUrlEncodedContent
Refer below code
using (HttpClient client = new HttpClient())
{
string baseUrl = "https://*******.com/****"
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "******");
jsonValues.Add("password", "******");
var contenta = new FormUrlEncodedContent(jsonValues);
var response = await client.PostAsync(baseUrl, contenta);
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
}
}

Scribe + Xing => Invalid OAuth signature

I'm trying to use scribe with XING and I'm always getting following answer:
Can't extract token and secret from this: '{"message":"Invalid OAuth signature","error_name":"INVALID_OAUTH_SIGNATURE"}'
I have a working login process, get back an oauth_token and an oauth_verifier and tried to to change the defaultly selected HMACSha1 Singature with a PlainText signature, but I'll always get the above mentioned result...
Any ideas on why this happens?
Using the default DefaultApi10a and XingApi from scribe always fails at the above mentioned step...
EDIT - Code
// Creating the service
// callback is needed to stop redirecting in the webview
OAuthService service = new ServiceBuilder()
.provider(XingApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://www.xing.com")
.build();
Step 1: get request token + auth url
RequestToken requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken );
Step 2: load the auth url in a webview + check the redirect url and cancel redirection based on callback
for example, redirection url look like following: http://www.xing.com?oauth_token=a2191ab84c9e0f85cf0c&oauth_verifier=4978
Step 3: extract oauth_token + oauth_verifier from returned url
String oauthToken = ...; // a2191ab84c9e0f85cf0c in the example
String oauthVerifier = ...; // 4978 in the example
Step 4: get access token => this fails
Token requestToken = new Token(oauthToken, oauthVerifier); // reusing the request token from above results in invalid request token answer from xing!
Verifier v = new Verifier(oauthVerifier);
Token accessToken = service.getAccessToken(requestToken, v);
Remove:
Token requestToken = new Token(oauthToken, oauthVerifier); // reusing the request token from above results in invalid request token answer from xing!
line from step 4.
You have to keep request token to retrieve access token using it and verifier (4 digits PIN) from Xing.
EDIT - code added:
OAuth10aService service = new ServiceBuilder()
.apiKey("44a4f9c1a9daa88f4da2")
.apiSecret("2fc8ca373dab772acc4de7ce22718f8fced6919c")
.callback("https://redirect.example.com")
.build(XingApi.instance());
final Token requestToken = service.getRequestToken();
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("Paste the verifier here");
System.out.print(">>");
Scanner in = new Scanner(System.in);
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
in.close();
// Trade the Request Token and Verfier for the Access Token
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token! " + accessToken);

Resources