Unable to get Refresh Token in Google Calendar Version 3 - c#

I am developing my for Google Integration in ASP.NET. I am tring to create a service using access token and refresh token. But i am unable to get the refresh token as i am just getting Access Token, Token Type and Expires in. Please check the below code for this.
private String ExchangeCodeWithAccessAndRefreshToken()
{
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(Convert.ToString(Session["URL"]));
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}";
string Code = Request.QueryString["Code"];
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
String ClientID = ConfigurationManager.AppSettings["clientID"].ToString();
String ClientSecret = ConfigurationManager.AppSettings["clientSecret"].ToString();
string param = string.Format(data, Code, ClientID, ClientSecret, redirect_uri_encode, grant_type);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
var jsonSerializer = new JavaScriptSerializer();
var tokenData = jsonSerializer.Deserialize<GoogleTokenModel>(result);
return tokenData.Access_Token;
}

Try setting access_type=offline in your URL:
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type=offline";

Related

WebRequests in C# OpenID Connect OAuth

I need an example of accessing an external API using OpenID Connect/OAuth authentication/authorization, and The supported OAuth flow is Authorization Code Flow with PKCE.
endpoints use REST technology over HTTPS
I know that I have to get the authorization code first, then ask for the authentication token.
They have the OpenID Connect in this URL:https://iam.efatura.cv/auth/realms/taxpayers/.well-known/openid-configuration.
I'm using C# winForm
I'm doing this and giving error 401.
try {
string url5 = "https://iam.efatura.cv/auth/realms/taxpayers/protocol/openid-connect/token";
string client_id = "";
string client_secret = "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url5);
webRequest.PreAuthenticate = false;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "multipart/form-data";
webRequest.Headers.Add("Authorization:" + Authorization(client_id, client_secret));
var request = "grant_type=client_credentials";
byte[] req_bytes = Encoding.ASCII.GetBytes(request);
webRequest.ContentLength = req_bytes.Length;
Stream strm = webRequest.GetRequestStream();
strm.Write(req_bytes, 0, req_bytes.Length);
strm.Close();
MessageBox.Show(webRequest.Headers.ToString());
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
String json = "";
using (Stream respStr = resp.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8))
{
//should get back a string i can then turn to json and parse for accesstoken
json = rdr.ReadToEnd();
rdr.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

.net core call REST API on my localhost to get token - getting badRequest

I have 2 programs on my localhost, one with REST API and another program that calls the api.
I'm trying to authenticate user(https://localhost:44301/token) with below function and getting badRequest.
the same is working when testing with postman.
baseUrl is "https://localhost:44301/";
static async Task<Uri> AddCartRecordAsync(CartsTable cartsTable)
{
string ResponseString = "";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(Utility.baseUrl + "token");
request.Accept = "application/json";
request.Method = "POST";
//Get credentials from config.
var username = "kkk#gmail.com";
var password = "Test123!";
Credentials cred = new Credentials()
{
username = username,
password = password,
grant_type = "password"
};
var myContent = JsonConvert.SerializeObject(cred);
var data = Encoding.ASCII.GetBytes(myContent);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
using (response = (HttpWebResponse)request.GetResponse())//BadRequest Here
{
ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
catch (Exception e)
{
string i = "df";
}
The common issues are :
1-Params Body Type
2-Authentication Type : if u have bearer type you should include bearer keyword before your token in the header before sending request like "token":"bearer AuthToken"
3-method type : get put post delete

How to call this Delete web api method in C#?

I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);

Implementing Last.fm authentication in Windows Phone 8

I need to implement last.fm authentication in my Windows Phone 8 application. Last.fm requires a POST request with https for successful login. Here is what I'm doing.
public async void GetMobileSession(string userName, string password, Action<LastFmAuthResponse> onCompletion)
{
string CORE_URL = "https://ws.audioscrobbler.com/2.0/";
var parameters = new Dictionary<string, string>();
parameters.Add("username", userName);
parameters.Add("password", password);
parameters.Add("method", "auth.getMobileSession");
parameters.Add("api_key", api_key);
string signature = GetSignature(parameters);
string comboUrl = string.Concat("method=auth.getMobileSession", "&api_key=", api_key,
"&username=", userName, "&password=", password, "&api_sig=", signature);
LastFmAuthResponse response = null;
byte[] pendingPostContent = Encoding.UTF8.GetBytes(comboUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(CORE_URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await requestStream.WriteAsync(pendingPostContent, 0, pendingPostContent.Length);
}
request.BeginGetResponse(new AsyncCallback(n =>
{
HttpWebResponse rawResponse = (HttpWebResponse)request.EndGetResponse(n);
string rawData = string.Empty;
using (StreamReader reader = new StreamReader(rawResponse.GetResponseStream()))
{
rawData = reader.ReadToEnd();
}
try
{
if (!string.IsNullOrEmpty(rawData))
{
response = CommonFunctions.GetObjectFromString<LastFmAuthResponse>(rawData);
}
}
catch
{
}
onCompletion(response);
}), null);
}
However the code is failing at request.BeginGetResponse It returns an error saying remote server could not be found. Can someone please point out what I'm doing wrong here?

Google Api get token request returns invalid_request

I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.

Categories

Resources