I need to make the following call in REST. Can anyone provide a C# sample on how to do this ?
From:
https://learn.microsoft.com/en-us/azure/active-directory/active-directory-protocols-oauth-code
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMw-DjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpi-zY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
RestSharp really did make creating these rest calls easier (thanks Soren).
string token = await GetAccessToken();
var client = new RestSharp.RestClient("https://login.microsoftonline.com/common/oauth2/v2.0");
var request = new RestRequest("token");
request.AddParameter("grant_type","authorization_code");
request.AddParameter("client_id", "edd7c078-...f5d4979c7f4e");
request.AddParameter("code", "Ma49210e1-5332-a5dc-4005-70411bf85fbe");
request.AddParameter("redirect_uri", "https://localhost:44333");
request.AddParameter("client_secret", "qZqxfjca6xg0scsNP67KATy");
request.Method = Method.POST;
request.AddHeader("Authorization", "Bearer " + token);
var response = client.Execute(request);
Related
I would like to update the message of redeem channel point. I do the request in insomnia and it works, but when I try do the same in C#, I receive a message error
'Request failed with status code BadRequest'.
Request on insomnia:
Code of c#:
var client = new RestClient($"https://api.twitch.tv/helix/channel_points/custom_rewards?broadcaster_id={broadcastid}&id=06c5ae77-2890-4a7f-a722-52b96062ef82");
var request = new RestRequest();
request.Method = Method.Patch;
request.AddHeader("Authorization", $"Bearer {Properties.Resources.OAuthToken}");
request.AddHeader("Client-ID", $"{Properties.Resources.userid}");
request.AddHeader("Content-Type", "application/json");
//request.AddBody("is_enabled", "true");
//request.AddBody("prompt", $"test");
request.AddBody("{\"is_enabled\": true,\"prompt\":\"test\"}");
request.RequestFormat = DataFormat.Json;
var response = await client.PatchAsync(request);
Console.WriteLine("");
The request is Patch, can read more about request there. But i think the problem is on request.
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.
I am trying to send Header and Request in post method using RestClient library but getting error:
Endpoint not found.
var client = new RestClient("http://xxxxxxxxxx/UIService.svc/xxxxxxxxx/xxxxx");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Authentication", jsonHeadEncrpt);
// request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", JsonReqEncrpt, ParameterType.RequestBody);
var responsed = client.Execute(request);
Response :Endpoint not found. Please see the service help page for constructing valid requests to the service
Guys Found the solution need to add request.Resource where need to assign the endpoint function..Now it is working fine
I am working to consume Drupal Rest Api using c#. I am using drupal 7.5 and utilising it's rest services/api following various resources.
I have been successful with google's postman to post the content but when I try to replicate it with c# code I am prompted with forbidden error saying: Access denied for user anonymous.
I am utilising rest-sharp to consume this API. I have researched quite a lot and haven't found solution yet,as well as haven't noticed anyone doing this work in c#.
Following is the code snippet that I have written based on postman
var client = new RestClient("drupasitename/rest/node");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", authorisation);
request.AddHeader("x-csrf-token", token);
request.AddHeader("cookie", cookie);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", "{\r\n \"type\":\"page\",\r\n \"title\":\"Page submitted via JSON REST\",\r\n \"body\":{\r\n \"und\":[\r\n {\r\n \"value\":\"This is the body of the page.\"\r\n }\r\n ]\r\n }\r\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
cookie and token are obtained after successful login attempt using c# code.
It would be great if anyone could provide a guidance to solve this issues.
Regards
All you need is adding UserAgent into http request header
I got the user information include the cookie & token .
private login_user LoginAsync(string username,string password)
{
try
{
RestClient client = new RestClient(base_url);
var request = new RestRequest("login", Method.GET);
request.AddHeader("Content-Type", "Application/JSON");
client.Authenticator = new HttpBasicAuthenticator(username, password);
var restResponse = client.Execute(request);
var content = restResponse.Content;
string context_modifytoken = content.ToString().Replace("X-CSRF-Token", "X_CSRF_Token");
var current_login_user = JsonConvert.DeserializeObject<login_user>(context_modifytoken);
current_login_user.data.session_name = restResponse.Cookies[0].Name;
current_login_user.data.session_id = restResponse.Cookies[0].Value;
return current_login_user;
}
catch (HttpRequestException ex) { throw ex; }
}
And the Post section:
RestClient client = new RestClient(base_url);
var request = new RestRequest("v1.0/barcodes", Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("X-CSRF-Token", current_user.data.X_CSRF_Token);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddHeader("cookie", current_user.data.session_name+"="+ current_user.data.session_id);
request.AddHeader("User-Agent", ver);
var queryresult = client.Execute(request);
has error :queryresult = "StatusCode: Forbidden, Content-Type: application/problem+json; charset=utf-8, Content-Length: -1)"
and Drupal log :
restful 2016-09-21 16:32 You do not have access to create a new Sample Barcode... Anonymous (not verified)
I used following to login to drupal
var client = new RestClient("drupalsitename/user/login");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
request.AddParameter("application/json", "{\"name\":\"username\",\n\"pass\":\"password\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This will provide you with necessary session and token info and then basically you can use those information to make the post, similar to that I have written in the question
This is the (modified) snippet that Postman gives for successful call to my page.
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);
But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200.
The same thing happens when I use httpclient in my app (403).
Use RestClient.Authenticator instead:
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me")
{
Authenticator = new HttpBasicAuthenticator("User", "Pass")
};
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Edit:
Since the issue (as mentioned in the comments) is the fact that RestSharp doesn't flow the authentication through redirects, I'd suggest going with a combination of HttpClient with a HttpClientHandler where you set the authentication to flow.
[Solution]
Use the below line for the header
Headers.Add("User-Agent: Other");