How to set Twitch TV channel title - c#

I am working on being able to have my custom chat bot to update my primary channel's title (status). I am following this post and I am trying to get the access_token from the REDIRECT_URI.
The URI that contains the redirect is:
https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=channel_editor
I have manually tested this with my CLIENT_ID and REDIRECT_URI set to http://localhost and I get this response from the above URI (which is what I want):
http://localhost/#access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&scope=channel_editor
I am trying to get the access_token from this URI, but I cant seem to get to it from the code below. My response is:
https://api.twitch.tv/kraken/oauth2/authenticate?action=authorize&client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost&response_type=token&scope=channel_editor
Code:
string clientID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string redirectURL = "http://localhost";
string url = string.Format("https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id={0}&redirect_uri={1}&scope=channel_editor",
clientID, redirectURL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirUrl = response.Headers["Location"];
response.Close();
// Show the redirected url
Console.WriteLine("You're being redirected to: " + redirUrl);
This is a console application

This is not directly related to c# but implementing it should be easy enough https://discuss.dev.twitch.tv/t/how-to-set-title/390/2

This twitch dev post helped me out until I got to the "Make the request" step. My problem was I needed to make the C# equivalent of this cURL command to change the channel's title:
curl -H 'Accept: application/vnd.twitchtv.v2+json'
-H 'Authorization: OAuth <access_token>'
-d "channel[status]=New+Status!&channel[game]=New+Game!"
-X PUT https://api.twitch.tv/kraken/channels/CHANNEL
Solution:
I decided to manually get the access_token from the authentication request by ctrl + c and ctrl + v the token from the URI given below and store it into my database:
http://localhost/#access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&scope=channel_editor
Then, I used Postman to generate my RestSharp code with the body request in JSON:
string accessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var client = new RestClient("https://api.twitch.tv/kraken/channels/CHANNEL_NAME");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "OAuth " + accessToken);
request.AddHeader("accept", "application/vnd.twitchtv.v3+json");
request.AddParameter("application/json", "{\"channel\":{\"status\":\"Hello World\"}}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Related

Authenticating against Bronto REST Api using RestSharp

I've set hallmonitor (OAuth 2.0 compliant service) in a Bronto sandbox, but using RestSharp I can't get the access token to be able to make further calls to the REST API.
I've been able to successfully use curl i.e.
curl -X POST -d "grant_type=client_credentials&client_id=CLIENTID&client_secret=CLIENTSECRET" https://auth.bronto.com/oauth2/token
I've tried a number of variations of the code below, but nothing seems to work, I always get an error response.
{
"error_description": "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).",
"error": "unauthorized_client"
}
Simplified sample code
var client = new RestClient("https://auth.bronto.com");
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
//client.Authenticator = new SimpleAuthenticator(CLIENT_ID, clientId, CLIENT_SECRET, secret);
RestRequest request = new RestRequest("/oauth2/token", Method.POST);
//request.AddHeader("Authorization", "Basic " + client);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter(GRANT_TYPE, CLIENT_CREDENTIALS);
//request.AddParameter(CLIENT_ID, clientId);
//request.AddParameter(CLIENT_SECRET, secret);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
Has anyone used RestSharp with Bronto REST API to successfully authenticate and get the access token?
Any help is much appreciated.

OAuth2 Bearer Token not getting sent with RestSharp call

Credentials are right, because I can get an API response using PS with the same client id and secret. The token isn't invalid, but it won't get attached correctly to the rest request
Unauthorized. Access token is missing or invalid
Here's my code:
var client = new RestClient(url);
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator("Bearer: " + OAuthToken);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
foreach (var paramName in parameters.Keys) {
request.AddParameter(paramName, parameters[paramName]);
}
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK) {
string rawResponse = response.Content;
dynamic deserializedResponse = new JsonDeserializer().Deserialize<dynamic>(response);
return deserializedResponse;
}
else {
Dictionary<string, string> returnData = new JsonDeserializer().Deserialize<Dictionary<string, string>>(response);
throw new Exception("Failed call to API Management: " + string.Join(";", returnData));
}
I've also tried using:
request.AddHeader("authorization", "Bearer " + OAuthToken);
request.AddHeader("authorization", string.Format("Bearer " + OAuthToken));
request.AddHeader("authorization", string.Format("Bearer: " + OAuthToken));
request.AddHeader("authorization", $"Bearer {OAuthToken}");
request.AddParameter("authorization, "Bearer " + OAuthToken", HttpRequestHeader);
request.AddHeader("authorization", "bearer:" + access + "");
None worked.
Following code worked for me:
var restClient = new RestClient(Url)
{
Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(accessToken, "Bearer")
};
As a result, the "Authorization" header will contain "Bearer {accessToken}"
I was not able to authenticate when I was using it like
request.AddHeader("Authorization", $"Bearer {axcessToken}");
instead this worked for me
client.AddDefaultHeader("Authorization", $"Bearer {axcessToken}");
You don't need the Authenticator.
First, you should decorate the controller or the action like below:
[Authorize(AuthenticationSchemes = "Bearer")]
public class ApiServiceController : Controller
{
}
or better than that:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class ApiServiceController : Controller
{
}
Then you should add token bearer as this line:
request.AddParameter("Authorization", $"Bearer {OAuthToken}", ParameterType.HttpHeader);
where OAuthToken is the value of the received token from login.
If you need more codes, just tell me ;)
Question is old but for any one coming to this again.. this is what worked for me:
My project was configured to use Https, and I was not sending an Https request so server was sending me back a response informing that I should be using a Https request instead. After that, RestSharp performs automatically a redirect using Https this time, but is not including the Authorization Header. Mor infor here: https://github.com/restsharp/RestSharp/issues/414
My solutions was just to change my web api Url to use Https
https://.../api/values
Not sure if this will help anyone, but in my case the problem was JWT issue time. I was using current time, and the server was a few seconds behind. I noticed that the JWT token was working when I was stepping through the code, but not when I was running it without pausing. I fixed the problem by subtracting 1 minute from JWT issue time.
Use
var client = new RestClient(URL);
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", accessToken));
I had the same issue in ASP.NET Framework. Using the AddParameter, as below, worked.
RestClient client = new RestClient(Url);
RestRequest request = new RestRequest(Method.POST);
request.AddParameter("token", _OsiApiToken);
request.AddParameter("value", value);
IRestResponse response = client.Execute(request);
Prior to the above (working version) I had the Url as...
String.Format("https://myorg.locator.com/arcgis/rest/services/something/?token={0}&value={1}", X, Y)
Strangely the latter String.Format() worked in one project but not in another. Weird.

How to pass API_KEY through HttpWebRequest

I'm trying to send curl request passing some headers and authentication info.
All information i want to send went successfully but I'm stuck with how to send the api key that should be used instead of the normal username/password manner.
when I use online curl websites to send the curl request, I put : after the api key and then everything works perfectly.
And this is what i want to do in C# using HttpWebRequest
This is the code I'm using in order to do that:
string credentials = String.Format("{0}:{1}", "API_KEY", "GivenApiKey: ");
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.website.com/test");
httpWebRequest.ReadWriteTimeout = 100000;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = "GivenUserAgent";
httpWebRequest.Credentials = new NetworkCredential("Authorization", authorization);
please any help?
You should put the Authorization in a Header so:
httpWebRequest.Headers["Authorization"] = "Bearer " + apikey;
Depending on the server you are contacting, you'll have to determine the input. In my case Bearer should be placed before the apikey.
As most servers use the following setup for authorization:
Authorization: <type> <credentials>

Docusign /oauth/token endpoint return page instead of json with bearer C#

I went through the OAuth2 proccess in DocuSign API, I follow all the steps using official docs, but when I tried to perform the request in order to get the the AccessToken I received an HTML as response, indicating something like "DocuSign is temporarily unavailable. Please try again momentarily." Although the http response is 200(OK), The weird stuff is when I test with the same values on Postman I get the correct response.
This is my code
public static DocuSignBearerToken GetBearerToken(string AccessCode, bool RefreshToken = false)
{
string AuthHeader = string.Format("{0}:{1}", DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var client = new RestClient("http://account-d.docusign.com");
client.Authenticator = new HttpBasicAuthenticator(DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var request = new RestRequest("/oauth/token", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("authorization", "Basic " + Base64Encode(AuthHeader));
if(!RefreshToken)
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=authorization_code&code={0}", AccessCode), ParameterType.RequestBody);
else
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=refresh_token&refresh_token={0}", AccessCode), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseString = response.Content;
DocuSignBearerToken Result = JsonConvert.DeserializeObject<DocuSignBearerToken>(responseString);
return Result;
}
Ok, this is awkward, reading the DocuSign docs they never specify if the authorization URL is http or https I assumed it was http, postman is smart enough to determine http or https when performs the request, my code doesn't, simply changing the Authorization URL from http:// to https:// solves the error.
If your tests using Postman work, then there is a problem with your code.
We've all been there, including me!
In these cases, I send my request to requestb.in to see what I'm really sending to the server. You'll find something is different from what you're sending via Postman.

How to send POST request in Xamarin?

I've built my backend in rails.
My email address is "sample#zmail.com" and it's already registered. The password is "28902890" here
After giving the following command in terminal
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://auth-agdit.herokuapp.com/api/v1/sessions -d "{\"user\":{\"email\":\"sample#zmail\",\"password\":\"28902890\"}}"
I get this response from my backend,
{"success":true,"info":"Logged in :) ","data":{"authentication_token":"iexGFwJ6HwERQZ3wJ4NG"}}
Now I need to get this data from my Android app.
I can get json by using WebClient().downloadString() method for simple json where authentication is not needed and the request method is GET.
Now I need to get the output Json for POST method.
How can I accomplish that?
There are several methods of doing this. You could use the Xamarin component called RestSharp. This will provide you with easy methods of interfacing with your backend.
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
// add parameters for all properties on an object
request.AddObject(object);
// execute the request
RestResponse response = client.Execute(request);
If you do want to simply use the WebClient class provided by the BCL you can use the WebClient.UploadString(string, string) method like so:
using (WebClient client = new WebClient())
{
string json = "{\"user\":{\"email\":\"sample#zmail\",\"password\":\"28902890\"}}";
client.UploadString("https://example.com/api/v1/sessions, json);
}
If you need more control over the request (such as setting accept headers, etc.) then you can use HttpRequest, see this question for an example of that.
This is how I did it:
WebClient wc = new WebClient();
string baseSiteString = wc.DownloadString("https://auth-agdit.herokuapp.com");
string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];
Console.WriteLine("CSRF Token: {0}", csrfToken);
Console.WriteLine("Cookie: {0}", cookie);
wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
wc.Headers.Add("X-CSRF-Token", csrfToken);
wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
string dataString = #"{""user"":{""email"":""email_here"",""password"":""password_here""}}";
// string dataString = #"{""user"":{""email"":"""+uEmail+#""",""password"":"""+uPassword+#"""}}";
byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
byte[] responseBytes = wc.UploadData(new Uri("https://auth-agdit.herokuapp.com/api/v1/sessions.json"), "POST", dataBytes);
string responseString = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responseString);
Try with this code:
Uri address = new Uri("http://example.com/insert.php");
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection["Name"] = "string-input";
var webClient = new WebClient();
webClient.UploadValuesAsync(address, "POST", nameValueCollection);

Categories