I have these settings:
Auth URL (which happens to be a
"https://login.microsoftonline.com/...") if that helps.
Access Token URL "https://service.endpoint.com/api/oauth2/token"
ClientId "abc"
Clientsecret "123"
I then need to make a get call using a bearer token in the header.
I can get this to work in Postman, but have hit a wall trying to work out how to implement it in C#. I've been using RestSharp (but open to others). It all seems so opaque, when I thought it'd be pretty straight forward: it's a console app, so I don't need bells and whistles.
Ultimately, I want my app to (programatically) get a token, then use that for my subsequent calls. I'd appreciate anyone pointing me to documentation or examples, that explains what I'm after clearly. Everything I've come across is partial or for services operating on a different flow.
Thanks.
In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).
Also, you should only need the access token URL. The form parameters are then:
grant_type=client_credentials
client_id=abc
client_secret=123
Code Snippet:
/* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */
var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:
request.AddHeader("authorization", "Bearer <access_token>");
The Rest Client answer is perfect! (I upvoted it)
But, just in case you want to go "raw"
..........
I got this to work with HttpClient.
"abstractly" what you are doing is
creating a POST request.
with a body of payload "type" of 'x-www-form-urlencoded'. ( see FormUrlEncodedContent https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=net-5.0 and note the constructor : https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent.-ctor?view=net-5.0)
and in the payload of 'type' : x-www-form-urlencoded, you are putting in certain values like the grant_type, client_id, client_secret etc.
Side note, try to get it working in PostMan, and then it is easier to "code it up" using the code below.
But here we go, code using HttpClient.
.......
/*
.nuget\packages\newtonsoft.json\12.0.1
.nuget\packages\system.net.http\4.3.4
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
private static async Task<Token> GetElibilityToken(HttpClient client)
{
string baseAddress = #"https://blah.blah.blah.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "myId";
string client_secret = "shhhhhhhhhhhhhhItsSecret";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
internal class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
}
Here is another working example (based off the answer above)......with a few more tweaks. Sometimes the token-service is finicky:
private static async Task<Token> GetATokenToTestMyRestApiUsingHttpClient(HttpClient client)
{
/* this code has lots of commented out stuff with different permutations of tweaking the request */
/* this is a version of asking for token using HttpClient. aka, an alternate to using default libraries instead of RestClient */
OAuthValues oav = GetOAuthValues(); /* object has has simple string properties for TokenUrl, GrantType, ClientId and ClientSecret */
var form = new Dictionary<string, string>
{
{ "grant_type", oav.GrantType },
{ "client_id", oav.ClientId },
{ "client_secret", oav.ClientSecret }
};
/* now tweak the http client */
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
/* try 1 */
////client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded");
/* try 2 */
////client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
/* try 3 */
////does not compile */client.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
////application/x-www-form-urlencoded
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, oav.TokenUrl);
/////req.RequestUri = new Uri(baseAddress);
req.Content = new FormUrlEncodedContent(form);
////string jsonPayload = "{\"grant_type\":\"" + oav.GrantType + "\",\"client_id\":\"" + oav.ClientId + "\",\"client_secret\":\"" + oav.ClientSecret + "\"}";
////req.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");//CONTENT-TYPE header
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
/* now make the request */
////HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
HttpResponseMessage tokenResponse = await client.SendAsync(req);
Console.WriteLine(string.Format("HttpResponseMessage.ReasonPhrase='{0}'", tokenResponse.ReasonPhrase));
if (!tokenResponse.IsSuccessStatusCode)
{
throw new HttpRequestException("Call to get Token with HttpClient failed.");
}
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
APPEND
Bonus Material!
If you ever get a
"The remote certificate is invalid according to the validation
procedure."
exception......you can wire in a handler to see what is going on (and massage if necessary)
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Net;
namespace MyNamespace
{
public class MyTokenRetrieverWithExtraStuff
{
public static async Task<Token> GetElibilityToken()
{
using (HttpClientHandler httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
using (HttpClient client = new HttpClient(httpClientHandler))
{
return await GetElibilityToken(client);
}
}
}
private static async Task<Token> GetElibilityToken(HttpClient client)
{
// throws certificate error if your cert is wired to localhost //
//string baseAddress = #"https://127.0.0.1/someapp/oauth2/token";
//string baseAddress = #"https://localhost/someapp/oauth2/token";
string baseAddress = #"https://blah.blah.blah.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "myId";
string client_secret = "shhhhhhhhhhhhhhItsSecret";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
/* overcome localhost and 127.0.0.1 issue */
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
if (certificate.Subject.Contains("localhost"))
{
HttpRequestMessage castSender = sender as HttpRequestMessage;
if (null != castSender)
{
if (castSender.RequestUri.Host.Contains("127.0.0.1"))
{
return true;
}
}
}
}
return false;
}
public class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
}
}
}
........................
I recently found (Jan/2020) an article about all this. I'll add a link here....sometimes having 2 different people show/explain it helps someone trying to learn it.
http://luisquintanilla.me/2017/12/25/client-credentials-authentication-csharp/
Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
namespace TestAPI
{
class Program
{
static void Main(string[] args)
{
string id = "xxx";
string secret = "xxx";
var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
dynamic resp = JObject.Parse(response.Content);
string token = resp.access_token;
client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("cache-control", "no-cache");
response = client.Execute(request);
}
}
}
I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken and we get additional features like Token Cache out-of-the-box. From the documentation:
Why use ADAL.NET ?
ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.
Here is the code snippet:
// Import Nuget package: Microsoft.Identity.Client
public class AuthenticationService
{
private readonly List<string> _scopes;
private readonly IConfidentialClientApplication _app;
public AuthenticationService(AuthenticationConfiguration authentication)
{
_app = ConfidentialClientApplicationBuilder
.Create(authentication.ClientId)
.WithClientSecret(authentication.ClientSecret)
.WithAuthority(authentication.Authority)
.Build();
_scopes = new List<string> {$"{authentication.Audience}/.default"};
}
public async Task<string> GetAccessToken()
{
var authenticationResult = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
return authenticationResult.AccessToken;
}
}
You may use the following code to get the bearer token.
private string GetBearerToken()
{
var client = new RestClient("https://service.endpoint.com");
client.Authenticator = new HttpBasicAuthenticator("abc", "123");
var request = new RestRequest("api/oauth2/token", Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{ \"grant_type\":\"client_credentials\" }",
ParameterType.RequestBody);
var responseJson = _client.Execute(request).Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
if(token.Length == 0)
{
throw new AuthenticationException("API authentication failed.");
}
return token;
}
This example get token thouth HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=password";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byte1.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
getreaderjson = reader.ReadToEnd();
}
My client is using grant_type=Authorization_code workflow.
I have below settings:
Auth URL (which happens to be a "https://login.microsoftonline.com/...") if that helps.
Access Token URL: "https://service.endpoint.com/api/oauth2/token"
ClientId: "xyz"
Clientsecret: "123dfsdf"
I then need to make a get call using a bearer token in the header. I tried all the above code sample, But whatever I will land on Microsoft - Sign in to you account" page as
"\r\n\r\n<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->\r\n<!DOCTYPE html>\r\n<html dir=\"ltr\" class=\"\" lang=\"en\">\r\n<head>\r\n <title>Sign in to your account</title>\r\n "
I am able to execute on Postman and I observed there are 2 calls in console.
GET call for Authorization Code
POST call with above Authorization Code appended in the call to the the Access token.
I tried to execute the above GET call in a separately in POSTMAN, when I do that I will be prompted with microsoftonline login page, when I enter my credentials I will get salesforce error.
if anyone can provide sample code or examples of Authorization_code grand_type workflow That will be very great help...
Clearly:
Server side generating a token example
private string GenerateToken(string userName)
{
var someClaims = new Claim[]{
new Claim(JwtRegisteredClaimNames.UniqueName, userName),
new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
};
SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
var token = new JwtSecurityToken(
issuer: _settings.Tokenizer.Issuer,
audience: _settings.Tokenizer.Audience,
claims: someClaims,
expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
(note: Tokenizer is my helper class that contains Issuer Audience etc..)
Definitely:
Client side getting a token for authentication
public async Task<string> GetToken()
{
string token = "";
var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();
var client = new HttpClient();
client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StatisticUserModel user = new StatisticUserModel()
{
Password = siteSettings.PopularSearchRequest.Password,
Username = siteSettings.PopularSearchRequest.Username
};
string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
token = await response.Content.ReadAsStringAsync();
return token;
}
You can use this token for the authorization (that is in the subsequent requests)
https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.
I tried this way to get OAuth 2.0 authentication token using c#
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetToken());
Console.Read();
}
/// <summary>
/// Get access token from api
/// </summary>
/// <returns></returns>
private static string GetToken()
{
string wClientId = "#######";
string wClientSecretKey = "*********************";
string wAccessToken;
//--------------------------- Approch-1 to get token using HttpClient -------------------------------------------------------------------------------------
HttpResponseMessage responseMessage;
using (HttpClient client = new HttpClient())
{
HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://localhost:1001/oauth/token");
HttpContent httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
});
tokenRequest.Content = httpContent;
tokenRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(wClientId + ":" + wClientSecretKey)));
responseMessage = client.SendAsync(tokenRequest).Result;
}
string ResponseJSON= responseMessage.Content.ReadAsStringAsync().Result;
//--------------------------- Approch-2 to get token using HttpWebRequest and deserialize json object into ResponseModel class -------------------------------------------------------------------------------------
byte[] byte1 = Encoding.ASCII.GetBytes("grant_type=client_credentials");
HttpWebRequest oRequest = WebRequest.Create("https://localhost:1001/oauth/token") as HttpWebRequest;
oRequest.Accept = "application/json";
oRequest.Method = "POST";
oRequest.ContentType = "application/x-www-form-urlencoded";
oRequest.ContentLength = byte1.Length;
oRequest.KeepAlive = false;
oRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(wClientId + ":" + wClientSecretKey)));
Stream newStream = oRequest.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
WebResponse oResponse = oRequest.GetResponse();
using (var reader = new StreamReader(oResponse.GetResponseStream(), Encoding.UTF8))
{
var oJsonReponse = reader.ReadToEnd();
ResponseModel oModel = JsonConvert.DeserializeObject<ResponseModel>(oJsonReponse);
wAccessToken = oModel.access_token;
}
return wAccessToken;
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------- Response Class---------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// De-serialize Web response Object into model class to read
/// </summary>
public class ResponseModel
{
public string scope { get; set; }
public string token_type { get; set; }
public string expires_in { get; set; }
public string refresh_token { get; set; }
public string access_token { get; set; }
}
}
Related
How can I get ID Token from custom token?
[Fact]
public void Get_ID_Token_For_Service_Account_Test()
{
using (Stream stream = new FileStream(ServiceAccountJsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
ServiceAccountCredential credential = ServiceAccountCredential.FromServiceAccountData(stream);
FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromServiceAccountCredential(credential),
ServiceAccountId = ServiceAccountId,
});
var uid = "Some UID";
var additionalClaims = new Dictionary<string, object>
{
{"dmitry", "pavlov"}
};
string customToken = FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid, additionalClaims).Result;
string idToken= null; // How to get this?
FirebaseToken token = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken, CancellationToken.None).Result;
Assert.NotNull(token);
Assert.True(token.Claims.ContainsKey("dmitry"));
}
}
I see samples for some other languages/platforms but not for C# - how to get ID token via current user here - Retrieve ID tokens on clients. But for C# neither UserRecord nor FirebaseAuth provides ID Token. Any pointers are much appreciated.
I have found the way to get the ID token in FirebaseAdmin integration tests - see method SignInWithCustomTokenAsync. The only thing I have to adjust was base URL: according to Firebase Auth REST API documentation it should be
https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken
The API KEY refers to the Web API Key, which can be obtained on the project settings page in your admin console.
So the adjusted code looks like this:
private static async Task<string> SignInWithCustomTokenAsync(string customToken)
{
string apiKey = "..."; // see above where to get it.
var rb = new Google.Apis.Requests.RequestBuilder
{
Method = Google.Apis.Http.HttpConsts.Post,
BaseUri = new Uri($"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken")
};
rb.AddParameter(RequestParameterType.Query, "key", apiKey);
var request = rb.CreateRequest();
var jsonSerializer = Google.Apis.Json.NewtonsoftJsonSerializer.Instance;
var payload = jsonSerializer.Serialize(new SignInRequest
{
CustomToken = customToken,
ReturnSecureToken = true,
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var parsed = jsonSerializer.Deserialize<SignInResponse>(json);
return parsed.IdToken;
}
}
Just started at a new company and we all use Jira, the customers are determined to not use it as they don't like it so I have decided to build a simple Windows Form when they can both Log tickets and get Updates and Comments in a nice simple UI.
Now I have never done any coding before 2 weeks ago so it has been a struggle to get my head around both C# and Rest (Have made scripts for basic IT fixes but never anything as complex as this!)
Back onto point, Set up and got a Rest API set up with a Rest Client but everytime I try pull data from a ticket on Jira I get the error:
{"errorMessages":["You do not have the permission to see the specified issue.","Login Required"],"errors":{}}
Here is the code from the Form:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new SimpleAuthenticator("username", "abc", "password", "123");
var request = new RestRequest(Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
And here is the code from the Rest Client itself:
public Restclient()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
}
private string logonAttempt;
public string makeRequest()
{
string strResponseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
String authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.Headers.Add("Authorization", authType.ToString() + " " + authHeader);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//Process the Response Stream... (Could be JSON, XML ot HTML etc...)
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}//End of Stream Reader
}
}//end of Response Stream
}
catch (Exception ex)
{
strResponseValue = "(\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if(response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
Now obviously I am expecting that I have missed something absolutely bigginer as like I said, I've never taken on a project like this before and had 0 experience.
Just looking for someone to bluntly tell me what I'm doing wrong
Changed to this as per answer:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new
RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("cdale!" + ":" + "Chantelle95!"));
request.AddHeader("Authorization", "Basic " + authHeader);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
By default with the Jira REST API, you can use Basic Authentication or OAuth2. I think that more easy way for you will be to use the Basic one.
I'm not sure why you have a class where you define your custom RestClient since the first block of code uses the RestSharp one from http://restsharp.org.
In this case, you will need to modify your authenticator:
client.Authenticator = new HttpBasicAuthenticator(userName, password);
And I think that you should remove the line where you specify a token. I don't think that it's required.
Finally, the class Restclient doesn't seem to be used, then remove it.
You could also uses what you have created in your custom RestClient and manually specify a Basic header:
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.AddHeader("Authorization", "Basic " + authHeader);
However, it's essentially the behavior of the HttpBasicAuthenticator class.
If you don't want to encode your credentials in every request here is how to do it using cookies.
When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.
public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
JiraCookieEndpointUrl,
new StringContent(myJsonUserNamePassword, Encoding.UTF8, "application/json"));
var json = response.Content.ReadAsStringAsync().Result;
var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
return jArr;
}
}
public class JiraCookie
{
public Session session { get; set; }
}
public class Session
{
public string name { get; set; }
public string value { get; set; }
}
When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:
{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}
Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using. Read the JIRA API documentation for the correct URL for the version you are using. I'm using the following:
https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session
Remember you'll have to store your cookie and use it on every subsequent request.
Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.
Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.
Reference: https://stackoverflow.com/a/49109192/7763903
I am trying to perform a Post to my WebAPI from a c# WPF desktop app.
No matter what I do, I get
{"error":"unsupported_grant_type"}
This is what I've tried (and I've tried everything I could find):
Also dev web api currently active for testing: http://studiodev.biz/
base http client object:
var client = new HttpClient()
client.BaseAddress = new Uri("http://studiodev.biz/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
with the following send methods:
var response = await client.PostAsJsonAsync("token", "{'grant_type'='password'&'username'='username'&'password'='password'");
var response = await client.PostAsJsonAsync("token", "grant_type=password&username=username&password=password");
After that failed, I did some googling and tried:
LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));
same result, so I tried:
req.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
await client.SendAsync(req).ContinueWith(respTask =>
{
Application.Current.Dispatcher.Invoke(new Action(() => { label.Content = respTask.Result.ToString(); }));
});
Note: I can make a successful call with Chrome.
Update Fiddler Result
Could someone please help me make a successful call to the above web api...
Please let me know if I can help clarify.
Thanks!!
The default implementation of OAuthAuthorizationServerHandler only accepts form encoding (i.e. application/x-www-form-urlencoded) and not JSON encoding (application/JSON).
Your request's ContentType should be application/x-www-form-urlencoded and pass the data in the body as:
grant_type=password&username=Alice&password=password123
i.e. not in JSON format.
The chrome example above works because it is not passing data as JSON. You only need this for getting a token; for other methods of your API you can use JSON.
This kind of problem is also discussed here.
1) Note the URL: "localhost:55828/token" (not "localhost:55828/API/token")
2) Note the request data. Its not in json format, its just plain data without double quotes.
"userName=xxx#gmail.com&password=Test123$&grant_type=password"
3) Note the content type. Content-Type: 'application/x-www-form-urlencoded' (not Content-Type: 'application/json')
4) When you use javascript to make post request, you may use following:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
See screenshots below from Postman:
Here is a working example I used to make this request of my local Web API application running on port 43305 using SSL. I put the project on GitHub as well.
https://github.com/casmer/WebAPI-getauthtoken
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;
namespace GetAccessTokenSample
{
class Program
{
private static string baseUrl = "https://localhost:44305";
static void Main(string[] args)
{
Console.WriteLine("Enter Username: ");
string username= Console.ReadLine();
Console.WriteLine("Enter Password: ");
string password = Console.ReadLine();
LoginTokenResult accessToken = GetLoginToken(username,password);
if (accessToken.AccessToken != null)
{
Console.WriteLine(accessToken);
}
else
{
Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
}
}
private static LoginTokenResult GetLoginToken(string username, string password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
//TokenRequestViewModel tokenRequest = new TokenRequestViewModel() {
//password=userInfo.Password, username=userInfo.UserName};
HttpResponseMessage response =
client.PostAsync("Token",
new StringContent(string.Format("grant_type=password&username={0}&password={1}",
HttpUtility.UrlEncode(username),
HttpUtility.UrlEncode(password)), Encoding.UTF8,
"application/x-www-form-urlencoded")).Result;
string resultJSON = response.Content.ReadAsStringAsync().Result;
LoginTokenResult result = JsonConvert.DeserializeObject<LoginTokenResult>(resultJSON);
return result;
}
public class LoginTokenResult
{
public override string ToString()
{
return AccessToken;
}
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "error")]
public string Error { get; set; }
[JsonProperty(PropertyName = "error_description")]
public string ErrorDescription { get; set; }
}
}
}
If you are using RestSharp, you need to make the request like this:
public static U PostLogin<U>(string url, Authentication obj)
where U : new()
{
RestClient client = new RestClient();
client.BaseUrl = new Uri(host + url);
var request = new RestRequest(Method.POST);
string encodedBody = string.Format("grant_type=password&username={0}&password={1}",
obj.username,obj.password);
request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
var response = client.Execute<U>(request);
return response.Data;
}
Had same issues but only resolved mine over secured HTTP for the token URL. See sample httpclient code. Ordinary HTTP just stop working after server maintenance
var apiUrl = "https://appdomain.com/token"
var client = new HttpClient();
client.Timeout = new TimeSpan(1, 0, 0);
var loginData = new Dictionary<string, string>
{
{"UserName", model.UserName},
{"Password", model.Password},
{"grant_type", "password"}
};
var content = new FormUrlEncodedContent(loginData);
var response = client.PostAsync(apiUrl, content).Result;
it my case, i m forget install install package Token.JWT, so you need install too in your project.
Install-Package System.IdentityModel.Tokens.Jwt -Version 6.7.1
It may be the cause of protocol
it's required https://
EX : https://localhost:port/oauth/token
jQuery.ajax({
"method": "post",
"url": "https://localhost:44324/token",
**"contentType": "application/x-www-form-urlencoded",**
"data": {
"Grant_type": "password",
"Username": $('#txtEmail').val(),
"Password": $('#txtPassword').val()
}
})
.done(function (data) { console.log(data); })
.fail(function (data) { console.log(data); })
//In Global.asax.cs (MVC WebApi 2)
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
I tried to implement Yahoo OAuth 2.0 with following guide: https://developer.yahoo.com/oauth2/guide/
I was able to authorize and I received Authorization Code but I sucked at step 4. When my code tries to exchange Authorization Code for Access Token using /get_token 401 Unauthorized Error is thrown.
{
"error": "invalid_grant"
}
According to https://developer.yahoo.com/oauth2/guide/errors/index.html invalid_grant means that an invalid or expired token was provided. I am little bit confused why the 401 is thrown.
Have somebody experienced similar issue?
public class YahooOAuthClient : OAuth2Client
{
private const string AuthorizeUrl = "https://api.login.yahoo.com/oauth2/request_auth";
private const string TokenEndpoint = "https://api.login.yahoo.com/oauth2/get_token";
private readonly string clientId;
private readonly string clientSecret;
public YahooOAuthClient(string clientId, string clientSecret)
: base("Yahoo")
{
this.clientId = clientId;
this.clientSecret = clientSecret;
}
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
var uriBuilder = new UriBuilder(AuthorizeUrl);
uriBuilder.AppendQueryArgument("client_id", this.clientId);
uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.ToString());
uriBuilder.AppendQueryArgument("response_type", "code");
uriBuilder.AppendQueryArgument("language", "en-us");
return uriBuilder.Uri;
}
protected override IDictionary<string, string> GetUserData(string accessToken)
{
return new Dictionary<string, string>
{
{"id", accessToken}
};
}
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
var postData = HttpUtility.ParseQueryString(string.Empty);
postData.Add(new NameValueCollection
{
{ "grant_type", "authorization_code" },
{ "code", authorizationCode },
{ "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
});
var webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));
webRequest.Headers.Add("Authorization", "Basic " + encoded);
using (var s = webRequest.GetRequestStream())
using (var sw = new StreamWriter(s))
sw.Write(postData.ToString());
using (var webResponse = webRequest.GetResponse())
{
var responseStream = webResponse.GetResponseStream();
if (responseStream == null)
return null;
using (var reader = new StreamReader(responseStream))
{
var response = reader.ReadToEnd();
var json = JObject.Parse(response);
var accessToken = json.Value<string>("access_token");
return accessToken;
}
}
}
}
This answer may be late but I ran into the same problem as you though I was implementing with PHP. This is what I realized was my error:
Intially my return_url is of the form
http://example.com/oauth_handle?route=something/path/like¶m1=value¶m2=value
I was implemting oauth for facebook, twitter(blah), google linkedin and yahoo. Google oauth api didn't like the route=something/path/like so I url-encoded it to
http://example.com/oauth_handle?route=something%2Fpath%2Flike¶m1=value¶m2=value
So that is the return_uri that was sent to the /request_auth endpoint as-is.
Then for the /get_token then parameter return_uri was url-encoded again which means I was now doing a double url-encoding for the route=something/path/like part which makes the return_uri different in the two requests.
Correcting this by doing url_encode just once solves my problem. Hope this helps!
I'm trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn't working the same way, returning 401 Unauthorized instead.
Here's the curl command as documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials"
UPDATE: Apparently the .Credentials doesn't do the trick, instead setting Authorization header manually works (see code)
Here's the code (trimmed to its essence):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language:en_US")
// this doesn't work:
**request.Credentials = new NetworkCredential("A****", "E****");**
// DO THIS INSTEAD
**string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**
**request.Headers["Authorization"] = "Basic " + authInfo;**
using (StreamWriter swt = new StreamWriter(request.GetRequestStream()))
{
swt.Write("grant_type=client_credentials");
}
request.BeginGetResponse((r) =>
{
try
{
HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here
....
} catch (Exception x) { .... } // log the exception - 401 Unauthorized
}, null);
This is the request from code captured by Fiddler (raw), there are no authorization parameters for some reason:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1
Accept: application/json
Accept-Language: en_US
Host: api.sandbox.paypal.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials
Hoping the following code help to anyone who is still looking for a good piece of cake to get connected to PayPal.
As many people, I've been investing a lot of time trying to get my PayPal token access without success, until I found the following:
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
This code works pretty well for me, hoping for you too. The credits belong to Patel Harshal who posted his solution here.
This Works using HttpClient...
'RequestT' is a generic for the PayPal request arguments, however it is not used. The 'ResponseT' is used and it is the response from PayPal according to their documentation.
'PayPalConfig' class reads the clientid and secret from the web.config file using ConfigurationManager.
The thing to remember is to set the Authorization header to "Basic" NOT "Bearer" and if and to properly construct the 'StringContent' object with right media type (x-www-form-urlencoded).
//gets PayPal accessToken
public async Task<ResponseT> InvokePostAsync<RequestT, ResponseT>(RequestT request, string actionUrl)
{
ResponseT result;
// 'HTTP Basic Auth Post' <http://stackoverflow.com/questions/21066622/how-to-send-a-http-basic-auth-post>
string clientId = PayPalConfig.clientId;
string secret = PayPalConfig.clientSecret;
string oAuthCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + secret));
//base uri to PayPAl 'live' or 'stage' based on 'productionMode'
string uriString = PayPalConfig.endpoint(PayPalConfig.productionMode) + actionUrl;
HttpClient client = new HttpClient();
//construct request message
var h_request = new HttpRequestMessage(HttpMethod.Post, uriString);
h_request.Headers.Authorization = new AuthenticationHeaderValue("Basic", oAuthCredentials);
h_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
h_request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
h_request.Content = new StringContent("grant_type=client_credentials", UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await client.SendAsync(h_request);
//if call failed ErrorResponse created...simple class with response properties
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
ErrorResponse errResp = JsonConvert.DeserializeObject<ErrorResponse>(error);
throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
}
var success = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<ResponseT>(success);
}
catch (Exception)
{
throw new HttpRequestException("Request to PayPal Service failed.");
}
return result;
}
IMPORTANT: use Task.WhenAll() to ensure you have a result.
// gets access token with HttpClient call..and ensures there is a Result before continuing
// so you don't try to pass an empty or failed token.
public async Task<TokenResponse> AuthorizeAsync(TokenRequest req)
{
TokenResponse response;
try
{
var task = new PayPalHttpClient().InvokePostAsync<TokenRequest, TokenResponse>(req, req.actionUrl);
await Task.WhenAll(task);
response = task.Result;
}
catch (PayPalException ex)
{
response = new TokenResponse { access_token = "error", Error = ex };
}
return response;
}
Paypal has deprecated TLS 1.1, and only accepts 1.2 now. Unfortunately .NET (prior to version 4.7) uses 1.1 by default, unless you configure it otherwise.
You can turn on TLS 1.2 with this line. I recomend placing it Application_Start or global.asax.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I too suffered from a lack of example code and various issues with response errors and codes.
I am a big fan of RestClient as it helps a lot with integrations and the growing number of RESTful API calls.
I hope this small snippet of code using RestSharp helps someone: -
if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
var client = new RestClient(payPalUrl) { Encoding = Encoding.UTF8 };
var authRequest = new RestRequest("oauth2/token", Method.POST) {RequestFormat = DataFormat.Json};
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
authRequest.AddParameter("grant_type","client_credentials");
var authResponse = client.Execute(authRequest);
// You can now deserialise the response to get the token as per the answer from #ryuzaki
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(authResponse.Content);