How to make wordpress cookie authentication? - c#

I am using json auth api to authenticate the user.
i am using my wordpress site hosted on 000webhost with https protocol.
When i am logging in i am getting this error message :
System.Net.WebException: The remote server returned an error: (401) Unauthorized
What I have tried:
var webRequest =(HttpWebRequest)WebRequest.Create("https://mahdii.000webhostapp.com/users/auth/generate_auth_cookie/?nonce=my_nonce&username=my_username&password=my_password");
webRequest.Method = "GET";
webRequest.ContentLength = 0; // added per comment
string autorization = "username" + ":" + "Password";
byte[] binaryAuthorization =System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("AUTHORIZATION", autorization);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}", webResponse.Headers);
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string s = reader.ReadToEnd();
Console.WriteLine(s);
reader.Close();
}
Please i need help,suggestions would be appreciated.
I am pretty sure all the url parameters are correct !

Related

How to get authorization code for Xero OAuth2.0

I'm using Xero with c# winforms. Xero released a new topic OAuth2.0 and they are providing sample only for web applications. But I didn't get authorization code. I'm getting an html page as response not the authorization code. Can anyone help me? Thanks for the help in advance.
Here is my current code for getting authorization code:
string XeroUrl = "login.xero.com/identity/connect/authorize?response_type=code&client_id=xxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ScopeLimit = "openid profile email accounting.transactions&state=123";
string URL = "https://" + XeroUrl + "&scope=" + ScopeLimit;
try {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL);
webRequest.AllowAutoRedirect = true;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.UseDefaultCredentials = false;
webRequest.PreAuthenticate = false;
HttpWebResponse response = null;
response = (HttpWebResponse)webRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd();
}

How to fetch classrooms from google classroom using API calls?

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.

HTTP Post method is not working for yammer api

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

TeamCity - Unable to authenticate via API

I've been struggling with authentication in TeamCity through the API lately. I can access the resources directly in my browser (http://usr:pw#teamcity:8111/httpAuth/app/rest/...), but doing so programmatically returns 401-Unauthorized.
WebRequest request = WebRequest.Create("http://user:pwd#teamcity:8111/httpAuth/app/rest/projects");
request.Method = WebRequestMethods.Http.Get;
try
{
request.Timeout = Timeout.Infinite;
WebResponse response = request.GetResponse(); //Returns 401:Unauthorized
I can use guestAuth(http://teamcity:8111/guestAuth/app/rest/projects) without any problem, so there should not be any problem with the WebRequest itself.
Does anyone have an idea?
Try to add your credentials and then make request.it will be get what you need.
var username = "abc";
var password = "123";
var encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);

Windows Live SDK Authorization

I'm working with Windows Live SDK from C# trying to invoke directly the rest service for getting my oAuth token, but instead I'm getting an 401 Error. Unauthorized.
I have my application registered as Desktop Application on https://manage.dev.live.com/ and published so I have my own Client ID and Secret Key.
From my desktop application I open an Internet Explorer Window for Live Login and get my Verification Code.
With that code, secret key and clientID I invoke AccessToken.aspx on this way:
try
{
string requestUrl = "https://consent.live.com/AccessToken.aspx";
// Request the access token.
string postData = string.Format("wrap_client_id={0}&wrap_client_secret={1}&wrap_verification_code={2}",
clientId,
secretKey,
verificationCode);
postData = HttpUtility.UrlEncode(postData);
byte[] postDataEncoded = System.Text.Encoding.UTF8.GetBytes(postData);
WebRequest req = HttpWebRequest.Create(requestUrl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataEncoded.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataEncoded, 0, postDataEncoded.Length);
WebResponse res = req.GetResponse();
string responseBody = null;
using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
{
responseBody = sr.ReadToEnd();
}
// Process FORM POST.
NameValueCollection responseCollection = System.Web.HttpUtility.ParseQueryString(responseBody);
return responseCollection["wrap_access_token"];
}
catch (Exception ex)
{
throw ex;
}
What I'm doing wrong?
Thanks in advance for any help provided.
The remote server returned an error: (401) Unauthorized

Categories