RestSharp: get authorize code by username and password automatically - c#

I have an API that deals with registered Azure app, so I would like to get the auth_code without letting the user enter email and password to be authorized because I have a user with full permission so whenever the user wants to generate an access token I would like to let the API consumer to be authorized automatically( Pass the credentials by code.)
RestClient restClient = new RestClient();
restClient.BaseUrl = new Uri("https://login.microsoftonline.com/common/oauth2/authorize");
RestRequest restRequest = new RestRequest(Method.GET);
restClient.Authenticator = new HttpBasicAuthenticator("MyEmail", "MyPassword");
IRestResponse restResponse = restClient.Execute(restRequest);
In the response, it returns an HTML code for Microsoft to login and authorizes the user, so how can I get the code by passing the email and password.
By the way this is the way postman issues a get request:
GET https://login.microsoftonline.com/common/oauth2/authorize?resource=MYURL&response_type=code&state=&client_id=MYCLIENTID&scope=&redirect_uri=MYREDIRECTURL

Related

Yahoo OAuth2 get_token return error 500 (internal server error)

I am following the Yahoo official documentation (https://developer.yahoo.com/oauth2/guide/openid_connect/getting_started.html). I can successfully get an authorization code after user logins with Yahoo. I am now at step 3, trying to exchange the authorization code for a token, but Yahoo keeps returning an http error 500.
To exchange the authorization code for the access token from Yahoo, I am using the following RestSharp syntax:
var client = new RestClient(provider.TokenUrl);
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddParameter("client_id", codeModel.clientId, ParameterType.GetOrPost);
request.AddParameter("client_secret", provider.Secret, ParameterType.GetOrPost);
request.AddParameter("code", codeModel.code, ParameterType.GetOrPost);
request.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost);
request.AddParameter("redirect_uri", codeModel.redirectUri, ParameterType.GetOrPost);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var response = client.Execute<TokenResponseModel>(request);
responde.data returns the following:
content: {"error":"ACCESS_TOKEN_GENERATION_FAILED","error_description":"Access token generation failed"}
StatusCode: InternalServerError
The official documentations states: "The request parameters below are transmitted using HTTP POST in the request body. You can, however, also send the parameters client_id and client_secret in the HTTP Headers instead".
I have tried both methods (clientid and secret as part of the body and as an Basic Authorization Header) and both return the same result.
When sending the clientid and secret as part of the Basic Authorization header, both parameters above are replaced by the following:
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(codeModel.clientId, provider.Secret);
As stated before, the only message returned by Yahoo is "internal server error".
Is there something wrong with the RestSharp syntax that could be causing this? Any other ideas will be greatly appreciated.
Needless to say, all parameters of the request contain the data they need.
Thanks
When you create your application profile at YDN you must make sure to select at least one API permission. For example try "Profiles (Social Directory) Read Public".
If your application has no API permissions then token generation will fail just the way you described.
If you already created an application with no permissions then you will have to delete it and create it again.

oauth2 authentication c# code is not working

I am trying to consume oauth2 api using auth code. In first step, i received auth by providing client id and secret, and now in 2nd step, i need access token using that auth code.
I tried below c# code
var client1 = new RestClient("https://ant.aliceblueonline.com/oauth2/token");
var request1 = new RestRequest(Method.POST);
request1.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request1.AddParameter("code", "xxxxxxxxxxxxxxxxx");
request1.AddParameter("grant_type", "authorization_code");
request1.AddParameter("redirect_uri", "https://ant.aliceblueonline.com/plugin/callback");
request1.AddParameter("client_id", "MM01418");
request1.AddParameter("client_secret", "xxxxxxxxxxxxxx");
IRestResponse response = client1.Execute(request1);
In response, I get
The OAuth 2.0 Client supports client authentication method "client_secret_basic", but method "client_secret_post" was requested. You must configure the OAuth 2.0 client's "token_endpoint_auth_method" value to accept "client_secret_post
Tried a lot but could not resolve it.
First of all as you're working with C# I would like to recommend you to use IdentityModel to interact with any OAuth2 authorization server or OpenId Connect Provider.
Let's start by the definition of a Client: A client is an application that is allowed to request acces tokens on behalf of the user. In your example your server runing the code you posted is the client.
To be able to use the token endpoint to request a new access_token a client must be able to prove its identity first, by providing a client_id and client_secret (like a user and password for clients).
There are two methods for providing this client credentials, from IdentityServer4 documentation about secrets:
Authentication using a shared secret
You can either send the client id/secret combination as part of the POST body:
POST /connect/token
client_id=client1& client_secret=secret& ...
..or as a basic authentication header:
POST /connect/token
Authorization: Basic xxxxx
In this case, the error response is saying that just one of those methods is allowed, which is Authentication header
So instead of passing your client_id and client_secret along your request body:
request1.AddParameter("client_id", "MM01418");
request1.AddParameter("client_secret", "xxxxxxxxxxxxxx");
you need to concat client_id and client_secret with a collon as separator like "MM01418:xxxxxxxxxxxxxxxx" and apply base64 codification. Then add it to your request as header, of the form Authorization: Basic TU0wMTQxODp4eHh4eHh4eHh4eHh4eHh4. You can do this in c# by using the following code:
var credentials = string.Format("{0}:{1}", clientId, clientSecret);
var headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);
or instead leave this low level details to a library like IdentityModel Nuget Docs that implements the correct requests for you depending on the case.

Call swagger API in C#

I have an API for getting data that is created in Swagger. I Only have an base URL and an username, password and a token for that. When I go to the URL it will go to a login page and after login, We can access a list of APIs and get data from that.
Now I need that to be done in C# using restsharp. So that I can get the result in JSON and can update the values to DB.
This is my code which I used in C#
var restClient = new RestClient("https://v3.fusesport.com/api/events/")
{
Authenticator = new HttpBasicAuthenticator("xxxxx", "xxxxx")
};
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/json");
IRestResponse response = client.Execute(request);
This is getting an connection closed error.
I tried the API in postman app in chrome, it is getting the below error.
{
"detail": "Authentication credentials were not provided."
}
This is the screenshot of postman call with token
Postman with token
This is the screenshot of postman call with basic authentication
enter image description here
Can you help me what I am doing wrong. I think the API is using session based authentication.
Thanks in Advance.
I think your headers are incorrect. Instead of
request.AddHeader("Token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
try adding
request.AddHeader("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b");

Retrieving token on Swagger

I need to retrieve token from link.
But when I enter valid username and password I do not see any token. Also I tried to retrieve it in my C# Android program.
`var client = new RestClient("https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData");
request.AddParameter("username", login);
request.AddParameter("password", password);
IRestResponse response = client.Execute(request);
var content = response.Content;`
There are a lot of data in output but there is no token. How can I get deal with it?
The request URL is wrong.
https://networkrail-uk-qa.traffilog.com/swagger/ui/index#!/User/User_LoginData
is just a documentation page (aka Swagger UI), not the actual request URL.
To find out the actual URL, use Swagger UI's "Try it out" feature: fill out the operation parameters and click "Try it out". It looks like the correct URL is
https://networkrail-uk-qa.traffilog.com/UK/api/User/Login?username={login}&password={password}
where the login and password need to be URL-encoded.
Also note the request HTTP method (POST), and that the parameters need to be passed in the query string. With all that in mind, your code should be:
var client = new RestClient("https://networkrail-uk-qa.traffilog.com");
var request = new RestRequest("UK/api/User/Login", Method.POST);
request.AddQueryParameter("username", login);
request.AddQueryParameter("password", password);
IRestResponse response = client.Execute(request);

Trello API OAuth can't find my app

I'm using Trello's Developer API's implementation of OAuth to post stuff to a list.
I've successfully made a request and got my oauth_token and oauth_token_secret back from https://trello.com/1/OAuthGetRequestToken
But when I call https://trello.com/1/OAuthAuthorizeToken, passing the oauth_token that I've just received, I get a response of 'App not found'.
Can anyone help?
EDIT: Here's what I'm getting back from https://trello.com/1/OAuthGetRequestToken
oauth_token=8d0e43fd0cc67726567d49ae5e818852&oauth_token_secret=[secret]
And here's the Authorization header I'm sending (escaped in C#)
"OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\""
Am I doing something wrong or is this an error on Trello's end?
EDIT: I'm using RestSharp to call the Trello API, as below:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
EDIT: Here's the complete RestSharp code:
var client = new RestSharp.RestClient("https://trello.com/");
var request = new RestSharp.RestRequest("1/OAuthAuthorizeToken", Method.GET);
Uri uri = new Uri(string.Format("{0}/{1}", client.BaseUrl, request.Resource));
string authHeader = GenerateAuthorizationHeader(uri);
//This is the output of GenerateAuthorizationHeader()
//string authHeader = "OAuth oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\", oauth_nonce=\"8335006\", oauth_timestamp=\"1414663625\", oauth_consumer_key=\"9612eaca23c7bdd3eca60dc8c2a8159c\", oauth_signature=\"M6sLyyfHGYXOtQnLJexDx96kbFo=\", oauth_token=\"8d0e43fd0cc67726567d49ae5e818852\"";
request.AddHeader("Authorization", authHeader);
The GenerateAuthorizationHeader method uses OAuth.OAuthBase to generate the TimeStamp and Signature for the OAuth request.
Looks like it might be a trello problem...
this user, had the wrong key by the sounds of things.
are you 100% sure that the key is correct.
Getting "App not found" from Trello Authentication
I had the same problem, the thing here is that OAuth is version 1.0
When you get the token and token secret from the first call you have to make your user to visit https://trello.com/1/OAuthAuthorizeToken not you.
In your case you have to redirect your user to https://trello.com/1/OAuthAuthorizeToken?oauth_token=8d0e43fd0cc67726567d49ae5e818852&scope=read,write,account
He will get a page where he can Allow the access. Then you will get a verification code in the page after the authorization to continue with your process (GetAccessToken).
You can try this as a test, in a real application you have to specify a callback url and an application name in the OAuthAuthorizeToken call.

Categories

Resources