WebRequests in C# OpenID Connect OAuth - c#

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());
}

Related

OAuth2.0 - Exchange authorisation code for access token

I'm trying to exchange an authorisation code for an access token using C# on HRMRC Making Tax Digital API. I'm able to get the authorisation code alright which I thought would be the difficult bit.
I've also been able to use Postman to exchange the authorisation code my app has obtained for the access token. See the attached screen shots of Postman and below is my C# :
uri = "https://api.service.hmrc.gov.uk/oauth/token"
body = "client_id=MyClientId&client_secret=MyClientSecret&code=MyAuthorisationCode&grant_type=authorization_code&redirect_uri=http%253A%252F%252Flocalhost%253A80%252F"
private static AccessTokens GetTokens(string uri, string body)
{
AccessTokens tokens = null;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/vnd.hmrc.1.0+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(body);
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
string json = reader.ReadToEnd();
reader.Close();
tokens = JsonConvert.DeserializeObj[1]ect(json, typeof(AccessTokens)) as AccessTokens;
}
return tokens;
}

WEB API C# REPONSE HANGS (HttpWebResponse)http.GetResponse()

Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

UnSupported Media Type when Calling REST Web Service

I am calling a REST web service which has given me this documentation
HTTP Method: POST
Path: /commit/{path}/add-node
Response Status 200, 302, 403, 404, 409, 503
Form Parameters
- name : attribute name
- message : commit message
Based on this documentation. I have written following C# code.
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
I also tried
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
var param = new { name = nodeName, message = commitMessage };
Stream reqStream = null;
string output = null;
try {
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
JsonConvert.SerializeObject(param)
);
request.ContentLength = buffer.Length;
reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
} catch (Exception ex) {
.....
}
Unfortunately in both cases, I get 415 Unsupported Media Type in both cases. What is wrong with my code?
The web Services is a REST based web service written in Java.
According to this forum post the ContentType property may not be supported from the Java web service. Are you sure it accepts application/json?

Wordnik authentication errors

I'm attempting to retrieve an authentication token from Wordnik by using the provided API. However, I cannot seem to get it to work; I seem to be stuck getting 401 and 403 errors.
The following is the code I am using to request authentication from the API:
string authRequest =
String.Format("http://api.wordnik.com//v4/account.json/authenticate/{0}",
this.userName);
HttpWebRequest request = WebRequest.Create(authRequest) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
// When this is added, I get 403 errors
///request.Headers.Add("api_key", APIKey);
string postData = "password=" + password;
byte[] encodedData = UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream stream = request.GetRequestStream();
stream.Write(encodedData, 0, encodedData.Length);
stream.Close();
string responseText;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadLine();
}
}
Can any of you tell me what I'm doing incorrectly?
Any input is appreciated.
You have a double slash in the request URL:
"http://api.wordnik.com//v4"

Categories

Resources