I need to implement a service for sending invitation mail to users.
I am following Samlman's artice.
I am trying to get a permanent token for Yammer API using the post method shown below.
I'm currently getting:
Error: 404 "server not found error".
There is no inner exception.
Do I need to pass authHeader?
If yes, then how do I send the authHeader?
string authUrl1 = string.Format("https://www.yammer.com/session?client_id={0}" , CLIENT_ID);
string postBody = string.Format(
"{0}{1}{2}{3}{4}{5}{6}",
"utf8=%E2%9C%93&authenticity_token=",
System.Web.HttpUtility.UrlEncode(authToken),
"&network_permalink=&login=",
HttpUtility.UrlEncode(userName),
"&password=",
pwd,
"&remember_me=off");
//make the first post for code
postResults = MakePostRequest(postBody, authUrl1);
private static string MakePostRequest(string postBody, string url, string authHeader = null, string contentType = null)
{
string results = string.Empty;
try
{
//get the session and yamtrack cookie
SetCookies();
wr = WebRequest.CreateHttp(url);
wr.Method = "POST";
wr.CookieContainer = cc;
//if an authHeader was provided, add it as a Bearer token to the request
if (!string.IsNullOrEmpty(authHeader))
wr.Headers.Add("Authorization", "Bearer " + authHeader);
byte[] postByte = Encoding.UTF8.GetBytes(postBody);
if (string.IsNullOrEmpty(contentType))
wr.ContentType = "application/x-www-form-urlencoded";
else
wr.ContentType = contentType;
wr.ContentLength = postByte.Length;
Stream postStream = wr.GetRequestStream();
postStream.Write(postByte, 0, postByte.Length);
postStream.Close();
wResp = (HttpWebResponse)wr.GetResponse();
postStream = wResp.GetResponseStream();
StreamReader postReader = new StreamReader(postStream);
results = postReader.ReadToEnd();
postReader.Close();
postStream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error in MakePostRequest: " + ex.Message);
}
return results;
}
The information in that blog is incorrect, it does not work and it is unsupported by Yammer. I'd advise you pre-obtain the token using a service account, store it somewhere safe, then pass it as an Authorization header in your POST and/or GET request. A very good example is shown here - http://blogs.technet.com/b/israelo/archive/2015/02/24/consuming-yammer-restful-api-with-angularjs-for-dummies.aspx
Related
I want to redirect a system to a centralized authentication server and I need to fill some parameters in headers and redirect to the authentication server completely. Using Web Client or Web Request I must return a value as a response to the requester ( They work as a listener ).
WebClient Send Request Example:
var values = new NameValueCollection();
values["clientId"] = clientId;
values["clientIP"] = currentIP;
byte[] response;
var resultResponse = string.Empty;
using (var client = new WebClient())
{
try {
response = client.UploadValues(url, values);
resultResponse = Encoding.Default.GetString(response);
}
catch (WebException e)
{
string exception = string.Empty;
if (e.Status == WebExceptionStatus.ProtocolError)
{
exception += ((HttpWebResponse)e.Response).StatusCode;
exception += ((HttpWebResponse)e.Response).StatusDescription;
}
}
}
Web Request Example
string method = "post";
WebRequest req = WebRequest.Create(uri);
req.ContentType = contentType;
req.Method = method;
req.Headers.Add("myhead", value);
req.ContentLength = jsonDataBytes.Length;
var stream = req.GetRequestStream();
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length);
stream.Close();
var response = req.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(response);
var respo = reader.ReadToEnd();
reader.Close();
response.Close();
return respo;
As you see in both methods the requester post the request and is waiting till receiving the response. I can not return to the requester system until I show two view to the user, get the username and passwords and finally process the information. I need to fill headers in a request, post it to the server and also redirect to the central authentication server. I searched a lot and found that it is impossible to post and redirect at a same time. Can you suggest any other methods to me?
So I am trying to fetch my classes from my google classroom into my application:
Here is my google url:
var Googleurl = "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=" + googleplus_redirect_url + "&prompt=consent&response_type=code&client_id=" + googleplus_client_id + "&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/m8/feeds/+https://www.googleapis.com/auth/drive+https://www.googleapis.com/auth/drive.appdata+https://www.googleapis.com/auth/drive.file+https://www.googleapis.com/auth/drive.metadata+https://www.googleapis.com/auth/classroom.courses+https://www.googleapis.com/auth/classroom.profile.emails+https://www.googleapis.com/auth/classroom.profile.photos+https://www.googleapis.com/auth/classroom.rosters+https://www.googleapis.com/auth/classroom.rosters.readonly&access_type=offline";
After this I request for the access codes through:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
I am able to get the access code as well as the refresh token all fine.
Now when I wish to fetch my classroom by:
string p="https://classroom.googleapis.com/v1/courses";
string auth = "Bearer "+access_token;
private bool GetClasses(string p,string auth)
{
using (var client = new WebClient())
{
var uri = new Uri(p);
//client.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer", auth);
string req="Authorization: "+ auth;
client.Headers.Add(req);
var response = client.DownloadString(uri);
}
return true;
}
This code return an error of type:System.Net.WebException: {"The remote server returned an error: (403) Forbidden."}
I have used the same access_token to get all other scopes as shown in the scopes parameter in mu Googleurl. However I am unable to access my classes even though I've added the respective scopes for it.
Apparently to use google classroom related functionalities we need to enable the google classroom Api. As silly as it may sound I was ignorant about it(As I had already enabled the google Api service). Just had to activate the classroom api and the code worked like a charm.
I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}
I need to allow user to enter a remote API url with basic authentication/ or a static token to POST the data from my application to the URL at specified intervals.
I tried setting the "HEAD" only but it does the GET operation and throws 405 - Method Not Allowed error for all the requests.
I would like to know if there is any way to validate the url and the credentials with given POST url.
I understand I can valid the the url but my concern is to ensure that I need to validate the basic auth credentials entered by the user is also correct.
Try this-
try
{
WebRequest tRequest = WebRequest.Create("YOUR API URL");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
//REQUIERED PARAMETERIZED DATA
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID));
tRequest.Headers.Add(string.Format("YOUR HEADER"));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
str = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
str = ex.Message;
}
I am triyng to get data from the Rest API. API wants 3 things to give authentication;
first one is "Accept:application/vnd.###.v1.0+json"
second one : "Content Type : application/json"
third one : Base64 encoded "userName:password" string
and I should pass these credentials for validation and authorization in custom header.I know there are a lot of thread on this site about this topic but I couldn't solve the problem from them.
Here is the code block :
public class McAfeeIPSManager
{
String URL = "https://serviceOfApi/sdkapi/session";
public void getWebRequest()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
String username = "user";
String password = "password1";
var request = HttpWebRequest.Create(URL) as HttpWebRequest;
request.Accept = "application/vnd.###.v2.0+json";
request.Method = "GET";
request.ContentType = "application/json";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization","Basic "+encoded);
try
{
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
string responseBody = responseReader.ReadToEnd();
// Console application output
System.Diagnostics.Debug.Write("Response Body ---> " + responseBody);
//Console.WriteLine(responseBody);
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.Write("Error : " + ex.Message);
Console.WriteLine("Error: {0}", ex.Message);
}
}
}
How can get data from WebAPI under these conditions?Can anybody help me?
You have no PreAuthenticate and credential ?
I have a code that may help you:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://pwmaffr2:8443/remote/system.delete?names=" + DeviceName + "");
request.Headers.Add("AUTHORIZATION", "Basic YTph");
request.ContentType = "text/html";
request.Credentials = new NetworkCredential(Username, Password);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
request.PreAuthenticate = true;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
);
StreamReader stream = new StreamReader(response.GetResponseStream());
string X = stream.ReadToEnd();
hmm in addition of what i post try deal with this it should work for you hope:
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("basic ", base64);
request.Headers.Add("Authorization", authorization);