Get OAuth2.0 Bearer Token from AuthURL and ClientID - c#

In Postman I am able to generate the Bearer token using
Callback URL
Auth URL
Client ID
How do I do the same using C# code?
This is the code I am running but the response body does not have the bearer token.
var client = new RestClient("AuthURL");
var requestToken = new RestRequest(Method.POST);
requestToken.AddHeader("cache-control", "no-cache");
requestToken.AddHeader("content-type", "application/x-www-form-urlencoded");
requestToken.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(requestToken);
string res = response.Content;

where is your username and password?
var client = new RestClient("http://example.com");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
might be a duplicate of this question
RestSharp HttpBasicAuthentication - example

Related

RestClient Digest Authentication C#

I am trying to make a post request using RestClient with Digest Authentication .
But I keep getting error :
Cannot load all required data from authenticateHeader. Data: Realm="api domain"&Nonce="7fe0990c20aaa812c5a0a725e3a01423"&Qop="""
My code
var client = new RestClient("ApiUrlPath");
client.Authenticator = new DigestAuthenticator("username","Password");
client.UseUtf8Json();
client.Timeout = -1;
var request = new RestRequest();
request.AlwaysMultipartFormData = true;
request.AddParameter("id", "2");
var response = client.Execute(request);
The request works in postman

Authentication Error while trying to get the DHL Interface to run

I've been trying to get the DHL interface up and running for some time now.
Unfortunately, there is already a lack of authentication.
Request:
client_id == AppID
client_secret = AppToken
var client = new RestClient("https://api.dhlecs.com/auth/v4/accesstoken");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", client_id);
request.AddParameter("client_secret", client_secret);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Response:
{"type":"https://api.dhlecs.com/docs/errors/401.0000007", "title":"Invalid
credentials"}
Does anyone have any idea why it doesn't work? Or am I calling something wrong?

RestSharp body always empty

I need to call a Post service with RestSharp
var client = new RestClient(url);
var request = new RestRequest(url,Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
);
var response = client.Post(request);
The problem is that the request's body is always null and the json body is added as a parameter
Any ideas?
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
seems to not accept json, even with the content-type set as "application/json"
My solution:
var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);
var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);
var response = client.Execute(request);

Converting HttpClient to RestSharp

I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.
client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;
This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
Am I missing something with authenticating?
This has fixed my problem:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization",
string.Format("Bearer " + access_token),
ParameterType.HttpHeader);
var response = client.Execute(request);
Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix
Try this
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:
private void InitializeClient()
{
_client = new RestClient(BASE_URL);
_client.DefaultParameters.Add(new Parameter("Authorization",
string.Format("Bearer " + TOKEN),
ParameterType.HttpHeader));
}

RestSharp HttpBasicAuthentication - example

I have a WPF client using RestSharp and WEB API Service. I try to use HttpBasicAuthenticator as follows:
RestRequest login = new RestRequest("/api/users/login", Method.POST);
var authenticator = new HttpBasicAuthenticator("admin","22");
authenticator.Authenticate(Client, login);
IRestResponse response = Client.Execute(login);
The POST request looks like this:
POST http://localhost/api/users/login HTTP/1.1
Authorization: Basic YWRtaW46MjI=
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.1.0.0
Host: dellnote:810
Content-Length: 0
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
How do I process this field, Authorization: Basic YWRtaW46MjI= on the server side? Do I get username and password from this header?
How do I return security token from server to client and save it on the client side?
I need to get simple authentication based on security token but cannot find example that describes all sides of this process. Can someone point me to some full example that includes client and server side (and uses RestSharp).
new SimpleAuthenticator("username", username, "password", password) did NOT work with me.
The following however worked:
var client = new RestClient("http://example.com");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
From RestSharp documentation:
var client = new RestClient("http://example.com");
client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar");
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
The URL generated for this request would be http://example.com/resource?username=foo&password=bar
So you get the password just as any other parameter (although, it's recommended to use POST method then GET, for security reasons).
As for the cookies, check this out:
https://msdn.microsoft.com/en-us/library/system.windows.application.setcookie.aspx
https://msdn.microsoft.com/en-us/library/system.windows.application.getcookie.aspx
Hope it helps
The following worked for me:
private string GetBearerToken()
{
var client = new RestClient("http://localhost");
client.Authenticator = new HttpBasicAuthenticator("admin", "22");
var request = new RestRequest("api/users/login", 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;
}
RestClient restClient = new RestClient(baseUrl);
restClient.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin","22");
RestRequest login = new RestRequest("/api/users/login", Method.POST);
IRestResponse response = restClient.Execute(login);
Alternative answer your first question about retrieval of Auth Header values (Server Side) from How can I retrieve Basic Authentication credentials from the header?:
private UserLogin GetUserLoginCredentials()
{
HttpContext httpContext = HttpContext.Current;
UserLogin userLogin;
string authHeader = httpContext.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
userLogin = new UserLogin()
{
Username = usernamePassword.Substring(0, seperatorIndex),
Password = usernamePassword.Substring(seperatorIndex + 1)
};
}
else
{
//Handle what happens if that isn't the case
throw new Exception("The authorization header is either empty or isn't Basic.");
}
return userLogin;
}
Usage of this method might be:
UserLogin userLogin = GetUserLoginCredentials();
Also have a look at: A-WebAPI-Basic-Authentication-Authorization-Filter
Alternative answer on second question about returning the token (Server Side):
var httpResponseMessage = Request.CreateResponse();
TokenResponse tokenResponse;
bool wasAbleToGetAccesToken = _identityServerHelper.TryGetAccessToken(userLogin.Username, userLogin.Password,
platform, out tokenResponse);
httpResponseMessage.StatusCode = wasAbleToGetAccesToken ? HttpStatusCode.OK : HttpStatusCode.Unauthorized;
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(tokenResponse),
System.Text.Encoding.UTF8, "application/json");
return httpResponseMessage;

Categories