OAuth2 grant_type missing - google-oauth

I am getting error that required parameter grant_type is missing in the request.
Using OAuth2 for Webserver application.
Please see below the code:
var httpClient : HTTPClient = new HTTPClient();
httpClient.setTimeout(3500);
httpClient.setRequestHeader("ContentType", "application/x-www-form-urlencoded");
httpClient.open("POST", "https://accounts.google.com/o/oauth2/token");
var param1:String = "code="+Encoding.toURI(pdict.CurrentHttpParameterMap.code.value.split('.')[0]);
var param2:String = "client_id="+pdict.session.custom.client_id;
var param3:String = "client_secret="+pdict.session.custom.client_secret;
var param4:String = "redirect_uri="+Encoding.toURI(pdict.session.custom.redirect_uri);
var param5:String = "scope=";
var param6:String = "grant_type=authorization_code";

Using below syntax i.e. passing variables as part of Request body solved it.
var client_secret : HTTPRequestPart = new HTTPRequestPart("client_secret", pdict.session.custom.client_secret);

Related

How to use WebProxy with RestSharp?

I would like to know how to use WebProxy with RestSharp. I am using version 108.0.1 and the code given below returns 407 when running locally from my workstation, which should use my credentials.
var client = new RestClient("https://www.google.com");
var proxy = new System.Net.WebProxy("http://mycorpproxy.com");
proxy.UseDefaultCredentials = true;
client.Options.Proxy = proxy;
var request = new RestRequest();
request.Method = Method.Get;
var response = client.Execute(request);
You need to specify the proxy in the options when you create the client, not after. In v107, the options object properties were init-only, but it fails on legacy SDKs, so we had to revert it to setters, but setting the options that are used to create an HttpClient instance after the client is created has no effect.
var proxy = new WebProxy("http://mycorpproxy.com") {
UseDefaultCredentials = true
};
var options = new RestClientOptions("https://www.google.com") {
Proxy = proxy
};
var client = new RestClient(options);

IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope

I have a client code implementation to consume a service with IEndpointBehavior to track request and response data.
everything was working fine till I implement bearer token using OperationContextScope.
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer " + accessToken;
var context = new OperationContext(client.InnerChannel);
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
var operationContext = new OperationContextScope(context);
BeforeSendRequest, AfterReceiveReply stops calling since I implemented token-based authentication and it is working when I remove OperationContextScope code used for adding a token to the header.
I need help to understand how can I use both (token inserting using OperationContextScope and IEndpointBehavior for message interceptor) together.
According to your description, I did the test and successfully used OperationContextScope and IEndpointBehavior together.You may put the code of OperationContextScope in front of the code of IEndpointBehavior, which will cause the code of IEndpointBehavior to fail.
Service1Client service1Client = new Service1Client();
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer";
var context = new OperationContext(service1Client.InnerChannel);
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
var operationContext = new OperationContextScope(context);
service1Client.Endpoint.Behaviors.Add(new Interceptor());
service1Client.GetUserData("Test");
The above code structure will cause this problem.
The correct code structure should look like this:
Service1Client service1Client = new Service1Client();
service1Client.Endpoint.Behaviors.Add(new Interceptor());
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Bearer";
var context = new OperationContext(service1Client.InnerChannel);
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
var operationContext = new OperationContextScope(context);
service1Client.GetUserData("Test");

Web api token based authentication:- Failed to decode token from base64 string to get user name and password

I am using Web Api Token Based Authentication using OWIN Middleware; the token is generated successfully but i can't decode it; e.g. i cannot extract user name and password from it;
Here is my configuration
my start up code
var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
my code that is ued to send the token is
static async Task RunAsync(JObject token)
{
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(1000000000000);
client.BaseAddress = new Uri("http://localhost/SampleApp/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token["token_type"].ToString(),
token["access_token"].ToString());
}}
my authetication code
var authenticationSchema = httpContext.Request.Headers["Authorization"];
if (!String.IsNullOrWhiteSpace(authenticationSchema))
authentication = AuthenticationHeaderValue.Parse(authenticationSchema);
if (authentication != null)
{
var unencoded = Convert.FromBase64String(authentication.Parameter);
var userpw = Encoding.GetEncoding("iso-8859- 1").GetString(unencoded);
var creds = userpw.Split(':');
return new Tuple<string, string>(creds[0], creds[1]);
}
and the code failed when trying to decode the code from base64 string
note:- my sample token is
3K8vHKHA2ZsKfKbvzUbo4a2sat2JLzvvyxCZ0KSD6s1wUS3t3oDPXuQ89aTmGpsG4ZL8O0cr8M9EUeZGtdM6FBwR7gLFcLZkTaimFGKyyZMNce9trQavVTzs6gam6qach1rPTLv_gIYGgPmM-401PZsr89BIXw4acTpJL3KbXs8y7PQ-o-eTV2IA8euCVkqC02iEnAzmS0SwhBouISCC-HvcNpE2aNixg4JXEt8EslU
you can see the attached for the exception
As far as I can see from the code, access token is sent plain to server; but you need to encode the access token on the client side like:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(token["token_type"].ToString(),
Convert.ToBase64String(Encoding.GetEncoding("iso-8859-1").GetBytes(token["access_token"].ToString())));
Then you can convert access token from base64 string on the server side. The access token string value you provided is not a valid Base64 string, so as expressed in the exception message.

Fastlink OAuth Process

Are there any .net sample apps that demonstrate a FastLink integration?
If not, is it possible for your to document the best way to authenticate using OAuth via .net/C# and output the correct iframe urls?
Can you please document this process without pointing me to:
This: https://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/Yodlee_FastLink_and_LAW_Guide/Yodlee_FastLink_Integration_Guide
Or this: https://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/Yodlee_FastLink_and_LAW_Guide/Yodlee_FastLink_Product_Guide
I've managed to get the 'Add Account' FastLink working successfully in the developer portal using C#.
Code is pasted below, I can add more detail if you need it.
public static string GetAddAccountFastLinkUrl()
{
var oauthAccessToken = (JObject)JsonConvert.DeserializeObject(GetYodleeRestResult("jsonsdk/OAuthAccessTokenManagementService/getOAuthAccessToken", new Dictionary<string, object>()
{
{"cobSessionToken", cobSessionToken},
{"userSessionToken", userSessionToken},
{"bridgetAppId", "10003200"}
}));
var oauth = new OAuth.OAuthBase();
var nonce = string.Empty;
var ts = oauth.GenerateTimeStamp();
var urlParams = "?access_type=oauthdeeplink&displayMode=desktop";
var baseUrl = "https://fastlink.yodlee.com/appscenter/fastlinksb/linkAccount.fastlinksb.action";
var url = new Uri(baseUrl + urlParams);
var consumerKey = "a458bdf184d34c0cab7ef7ffbb5f016b";
var consumerSecret = "1ece74e1ca9e4befbb1b64daba7c4a24";
var token = oauthAccessToken["token"].ToString();
var tokenSecret = oauthAccessToken["tokenSecret"].ToString();
var httpMethod = "GET";
var normalizedUrl = "";
var normalizedRequestParameters = "";
var sig = string.Empty;
while (true)
{
nonce = oauth.GenerateNonce();
sig = oauth.GenerateSignature(url
, consumerKey
, consumerSecret
, token
, tokenSecret
, httpMethod
, ts
, nonce
, OAuth.OAuthBase.SignatureTypes.HMACSHA1
, out normalizedUrl
, out normalizedRequestParameters);
if (!sig.Contains('+'))
{
break;
}
}
var fastLinkUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + sig;
return fastLinkUrl;
}
For the error you are receiving:
I keep getting this error after attempting OAuth and browsing to the
fastlink page
?oauth_token=e9784744d0ff4ce09a47a3c88e15097e&oauth_error_problem=system_error&o‌​auth_error_code=415&gws_rd=ssl
If you are already a customer then,I would suggest you to file a Service Request using Yodlee Customer Care tool.
Apart from that here are few suggestions:
Please look out for any extra space or characters while creating OAUTH signature if there would be something unwanted characters or white spaces even then it will not work.

How to consume REST service from a MVC 4 web application?

Can someone give me pointers on how to How to consume an external REST service from a MVC 4 web application? The services rely on an initial call with credentials base 64 encoded, then returns a token which is used for further web service queries.
I cannot find an easy primer on how to do this kind of thing, could someone help please?
I have all this working in classic ASP & JQuery but need to move over to an MVC 4 web application.
You could use the HttpClient class. Here's an example of how you could send a GET request and use Basic Authentication:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
var buffer = Encoding.ASCII.GetBytes("john:secret");
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/authenticate").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}
Once you have retrieved the access token you could make authenticated calls:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
string accessToken = ...
var authHeader = new AuthenticationHeaderValue("Bearar", accessToken);
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/bar").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}