OAuth2.0 - Exchange authorisation code for access token - c#

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

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

Yahoo api for fantasy sports. Cannot figure how to use access token

I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}

C# - Request Json File with authorization key (cURL example)

I'm trying to do a HTTP GET request for a json file from an api in a C# application. I'm having trouble getting the authorization, request headers and the webresponse (.GetResponse not working).
The example on the api's site is in curl.
curl -H "Authorization: Bearer ACCESS_TOKEN" https://erikberg.com/nba/boxscore/20120621-oklahoma-city-thunder-at-miami-heat.json
Here is my request method, which will also include JSON deseralization
public static string HttpGet(string URI)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
// Not sure if the credentials input is the correct
string cred = $"{"Bearer"} {"ACCESS_TOKEN_IS_A_GUID"}";
req.Headers[HttpRequestHeader.Authorization] = cred;
req.Method = "GET";
// GetResponse() is "red", won't work.
WebResponse response = req.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd().Trim();
}
}
EDIT It was resolved. The problem was that the request was for a GZIP file and that had to be decompressed
var request = (HttpWebRequest)WebRequest.Create(requestUri);
request.UserAgent = userAgent;
request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Get;
request.Headers[HttpRequestHeader.Authorization] = bearer;
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
var response = (HttpWebResponse) request.GetResponse();
string jsonString;
using (var decompress = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (var sr = new StreamReader(decompress))
jsonString = sr.ReadToEnd().Trim();
}
_Game = JsonConvert.DeserializeObject<Game>(jsonString);
You are not getting it because you don't have access.
The cURL command from API's site(that you mentioned in your question) gives the following JSON
{
"error" : {
"code" : "401",
"description" : "Invalid access token: ACCESS_TOKEN"
}
}
And so does the following code:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("URL");
req.UserAgent = "Bearer";
WebResponse response = req.GetResponse();
So what you need is a valid username/password or userAgent. You might want to contact the site for that.

Azure AD Graph API add member to group

I am trying to add a member to a group using the aad graph api and I am keep getting 404.
A similar code works for me when I am trying to get the group members.
This is the code:
string requestUrl = string.Format("https://graph.windows.net/{0}/groups/{1}/$linkes/members?api-version=2013-04-05", tenantName, group.ObjectId);
string postData = string.Format("\"url\":\"https://graph.windows.net/{0}/users/{1}?api-version=2013-04-05\"", tenantName, user.ObjectId);
HttpWebRequest webRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = authenticationResult.CreateAuthorizationHeader();
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";
webRequest.Host = "graph.windows.net";
webRequest.ContentLength = postData.Length;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
string jsonText;
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (var streamReader =
new StreamReader(httpResponse.GetResponseStream()))
{
jsonText = streamReader.ReadToEnd();
}
I know there are other ways to do the same work, for example using the graph connection, but I prefer to use this way because it should work for roles as well.
Thanks
Your URL does seem to have a typo: $linkes. Should be $links.

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