I am trying to get user token and build the URL so that user need not login everytime they click the file. below is my code.
My question is do I need to pass whole of the token value shown below or??
The token value I am getting is
symmetric:algorithm:QUVT:keyid:NTZkYTNkNmI=:data:7P9aJHzkfGTOlwtotuWGaMqfU9COECscA9yxMdK64ZLa298A3tsGlHKHDFp0cH+gn/SiMrwKfbWNZybPXaltgo5e4H4Ak8KUiCRKWfS68qhmjfw69qPv9ib96vL3TzNORYFpp/hrwvp8aX4CQIZlBA==
The problem is, once i copy the URL and past it in the browser, it is taking me to the login page. Though I am not getting any errors, it should take users directly to the imageviewer but instead it takes me to login page, if I login it is opening the file correctly.
What am I doing wrong?
string text = "";
string userName = "userName";
string pwd = "*****";
fileNetID = "{5FCE7E04-3D74-4A93-AA53-26C12A2FD4FC}";
Uri uri = null;
string workplaceURL = "http://filenet:9081/WorkPlaceXT";
uri = new Uri(workplaceURL + "/setCredentials?op=getUserToken&userId=" + this.encodeLabel(userName) + "&password=" + this.encodeLabel(pwd) + "&verify=true");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(uri);
System.Net.WebResponse webResponse = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
String token = streamReader.ReadToEnd();
string contentURL = string.Empty;
contentURL = workplaceURL + "/getContent?objectType=document&impersonate=true&objectStoreName=OBJECTSTORE&id=" + HttpUtility.UrlEncode(fileNetID);
contentURL += "&ut=" + HttpUtility.UrlEncode(encodeLabel(token));
return contentURL;
Here is my function, you can see the last couple lines how I unroll the token at the end:
public static string getCEUserToken(string baseURL, string uid, string pwd)
{
string UserToken = "";
System.Net.WebRequest request = System.Net.WebRequest.Create(baseURL + "/setCredentials?op=getUserToken&userId=" + uid + "&password=" + pwd +
"&verify=true");
request.Method = "POST";
System.Net.WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
byte[] token = new byte[response.ContentLength];
stream.Read(token, 0, (int)response.ContentLength);
response.Close();
foreach (byte chr in token)
UserToken += System.Convert.ToChar(chr);
return System.Web.HttpUtility.UrlEncode(UserToken);
}
Related
I have read and read and played with this code inside out and I still cant work out how to get the refresh token. This in c#
I have tried different combo of access_type, prompt and approval_prompt params.
I keep revoking access by my user to the app, so when the auth code is being requested it does ask for myself to approve the app to be able to access.
I just want to get the refresh token so i can store it and keep refreshing.
here is the code below. I have removed the parts to get the auth code, but if it is needed i can add in. I wonder if anyone can simply spot something simply wrong.
string GetJsonFromAPICall(string p_url,string p_post_data, string p_b64_id_secret)
{
//string C_TOKEN_URL = "https://oauth2.googleapis.com/token";
string l_auth_string = "Basic " + p_b64_id_secret;
print("p_post_data = ", p_url + "?"+p_post_data);
print("Authorization", l_auth_string);
HttpWebRequest request = WebRequest.Create(p_url) as HttpWebRequest;
string postData = p_post_data;// "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
request.Headers.Add("Authorization", l_auth_string);
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
print("pos 20 in GetJsonFromAPICall");
print("length ", data.Length.ToString());
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
string getAccessToken(string p_b64_id_secret, string p_auth_code, string p_redirect_url)
{
//string l_url = "client_id="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_ID + "&client_secret="+ p_C_GBQ_ONLINE_APP_APP_CLIENT_SECRET + "access_type=offline&prompt=consent&grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
string l_params = "grant_type=authorization_code&code=" + p_auth_code + "&redirect_uri=" + p_redirect_url;
l_params += "&access_type=offline";
l_params += "&prompt=consent";
l_params += "&approval_prompt=force";
//return GetJsonFromAPICall("https://oauth2.googleapis.com/token", l_params, p_b64_id_secret);
return GetJsonFromAPICall("https://www.googleapis.com/oauth2/v4/token", l_params, p_b64_id_secret);
}
var credentials = string.Format("{0}:{1}", C_GBQ_ONLINE_APP_APP_CLIENT_ID, C_GBQ_ONLINE_APP_APP_CLIENT_SECRET_ID);
var b64_id_secret = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
string l_auth_code = "xxxxx"; // worked out successfully earlier
l_json_returned = getAccessToken(p_b64_id_secret, l_auth_code, C_GBQ_ONLINE_APP_REDIRECT_URL);
the returned json is
l_json_returned = : {
"access_token": "FFFFFFFF",
"expires_in": 3569,
"scope": "https://www.googleapis.com/auth/cloud-platform.read-only https://www.googleapis.com/auth/bigquery",
"token_type": "Bearer"
}
My application connects to Jira for data extraction. To do that, I used the following code:
public string RunQuery(JiraRessource resource, string project_id, int startAt, int maxResults, string method = "GET")
{
string url = string.Format(m_BaseUrl);
if (project_id != null)
{
string jql = "search?jql=project=" + project_id;
url = string.Format("{0}{1}", url, jql);
}
string jqr = "&startAt=" + startAt + "&maxResults=" + maxResults;
url = string.Format("{0}{1}", url, jqr);
Console.WriteLine(url);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
string base64Credentials = GetEncodedCredentials();
//string base64Credentials = WindowsIdentity.GetCurrent().Token.ToString();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
string result = string.Empty;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", m_username, m_password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
The user has to enter the username and the password to connect. I want to change that in order to connect directly using windows credentials. I have no idea on how to do that. Is it possible? If it is, how can I do that?
WebRequest class has a Credentials property. You can set it with a new NetworkCredential object. You can also set it to logged in windows user. Sample code;
request.Credentials = new NetworkCredential(user, pwd, domain);
or
request.Credentials = CredentialCache.DefaultNetworkCredentials;
How do I test if user supplied correct username/password for basic authentication?
I have this code to retrieve a page. If authentication is valid, it works fine
public static bool can_login(string user_name, string password)
{
WebResponse response = null;
StreamReader reader = null;
string result = null;
string login_url = "https://httpbin.org/basic-auth/user/passwd";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(login_url);
request.Method = "GET";
// Set the basic auth
string authInfo = user_name + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
response = request.GetResponse(); // Throws System.Net.WebException if login invalid
reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
return false;
}
Is there a foolproof way to test for correctness or should I just catch exception and hope its about the credentials?
I want to login to my MyBB forum with my console application, but I get an error with my code
Default parameter value for 'postData' must be compile-time constant
I can fix it rather easy if I set my Username and Password to be a const string, but than I can't use Console.ReadLine(); so I would have to hard code the username and password which I don't think is such a good idea.
This is my code:
public string Username = Console.ReadLine();
public string Password = Console.ReadLine();
public const string ForumUrl = "forum.smurfbot.net";
static void Main(string[] args)
{
}
public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
byte[] postBytes = Encoding.ASCII.GetBytes(postData);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string sReturn = sr.ReadToEnd();
sr.Dispose();
return sReturn;
}
Why set a default value for it in the first place? This is not how functions work!
Use separate arguments and perform the string concatenation inside your function.
public string MakePostRequest(string url, string Username, string Password, string ForumUrl)
{
string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login"
...
}
For a method with a name as generic as "MakePostRequest" having a default URL or default POST data sounds very strange.
To be honest, I'd expect it to accept just a URL and a mapping for the POST data and then it's up to the caller to passes the proper data for that request.
C# does allow setting defaults other than constants, so you can't use fields / other parameters. For url it is okay, since that is a constant value. The concatenated string for postData isn't allowed.
An option would be to set the default to null, and check for it in your method. That is allowed:
public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = null)
{
if (string.IsNullOrEmpty(postData))
{
postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login";
}
I am trying to implement 500px API with C#. I am able to authenticate user with 500px API but I am unable to get the access_token in exchange of response_token which leaves my third step of Oauth 1.0 incomplete. I am able to authorize user and get oauth_token and oauth_verifier but when I use this oauth_token for making following request :-
https://api.500px.com/v1/oauth/access_token
500 Internal Server Error along with the following screen gets thrown
I have debugged my code like thousand times, tried different ways to form URL, added various parameters to the request but no help. I am very badly stuck as almost no information is available on 500px developer website or on web for using this api in C#. I have reached a dead-end!
Following is my code:-
1.]For requesting token and authorizing user :-
string normalizedUrl;
string normalizedRequestParameters;
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
Uri uri = new Uri("https://api.500px.com/v1/oauth/request_token");
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
string timeStamp = myOAuth.GenerateTimeStamp();
string nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
string signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret,
"", "", "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
string authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl = new Uri(authorizationUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(signInUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stIn = new StreamReader(response.GetResponseStream());
string responseString = stIn.ReadToEnd();
stIn.Close();
//oauth_token=cf40227bb7ede4d6e56ff790324761b3&oauth_token_secret=0bcb59dff2c1d095739c86c534fc62d7ed224fecfe8744d48c9c95f36211382f
if (responseString.Contains("oauth_token=") && responseString.Contains("oauth_token_secret="))
{
String RespToken = responseString.Split('&')[0].Replace("oauth_token=", "");
String RespSecret = responseString.Split('&')[1].Replace("oauth_token_secret=", "");
uri = new Uri("https://api.500px.com/v1/oauth/authorize");
timeStamp = myOAuth.GenerateTimeStamp();
nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret, RespToken
, RespSecret, "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
Console.WriteLine("Signature=="+signature);
authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl1 = new Uri(authorizationUrl);
webBrowser1.Navigate(signInUrl1);
}
2.]After User clicks on Authorise this application for getting access_token:-
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string parameters;
string normalizedUrl;
string normalizedRequestParameters;
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
if (e.Url.ToString().Contains("https://www.xyz.com/"))
{
String url = (e.Url.ToString()).Replace("https://www.xyz.com/?","");
if( url.Contains("oauth_token="))
{
string OAuthToken = url.Split('&')[0].Replace("oauth_token=", "");
var uri = "https://api.500px.com/v1/oauth/access_token";
OAuthBase oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timeStamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(new Uri(uri), consumerKey, consumerSecret,
OAuthToken, String.Empty, "POST", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
signature = HttpUtility.UrlEncode(signature);
var requestUri = normalizedUrl + "?" + "oauth_callback=https://www.xyz.com" +"?"+ normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Console.WriteLine(requestUri);
var request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
// request.ContentType = "application / x - www - form - urlencoded";
//request.Credentials = CredentialCache.DefaultCredentials;
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();
}
}
catch(Exception ex)
{
Console.Writeln(ex.toString());
}
}
Now following is the line where my code is breaking:-
var response = request.GetResponse();
Completely at my wits end on this issue, not able to get to the root of it. Any help any directions will be highly appreciated. Any suggestions would be of great help!!
Thanks a ton in advance!
Here's what to do:
Use GET rather than POST (POST may work; I've not tried it and have had little success with 500px and POSTing)
Include the oauth_verifier you received during the authorisation step in the query URL
Sign the entire query using your consumer key and request token secret (returned in step 1)
Code snippet which should return "oauth_token=...&oauth_token_secret=..." in the HTTP reply body.
Make sure your OAuth implementation doesn't strip out any parameters beginning with "oauth_"! Mine was and it was stripping out the oauth_verifier parameter which is required by 500px.
OAuth.OAuthBase oauth = new OAuth.OAuthBase();
string strUrl = "";
string strParams = "";
string signature = oauth.GenerateSignature(new Uri(API_URL + "oauth/access_token?oauth_verifier=" + this.oauthVerifier),
this.consumerKey, this.consumerSecret, this.oauthToken, this.requestTokenSecret,
"GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(),
OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out strUrl, out strParams);
string authorizationUrl = strUrl + "?" + strParams + "&oauth_signature=" + System.Web.HttpUtility.UrlEncode(signature);
Debug.WriteLine("url>" + authorizationUrl);
Response reply = SendGetRequest(authorizationUrl);
if (reply.Success)
{
Debug.WriteLine("access_token>" + reply.Content);