using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
public partial class _Default : System.Web.UI.Page
{
protected string googleplus_client_id = "clientid";
protected string googleplus_client_sceret = "id";
protected string googleplus_redirect_url="http://localhost"; // Replace this with your Redirect URL; Your Redirect URL from your developer.google application should match this URL.
protected string Parameters;
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
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);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (Exception ex)
{
//throw new Exception(ex.Message, ex);
Response.Redirect("index.aspx");
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
Response.Redirect(Googleurl);
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
// You will get the user information here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
I don't know from where i can store the user information in my table,
actually I don't know about google authentication and i find ths=is code on stackoverflow
I just want to store all the information in a table and if a user is logged in for the first time the page should be redirected to new user page and if the user is old user the page should redirect to welcome page
To start with, I definitely agree that Google's documentation is a murky business.
There are a couple of different ways in which you can validate the integrity of the ID token on the server side (btw this is the page you're looking for):
"Manually" - constantly download Google's public keys, verify signature and then each and every field, including the iss one; the main advantage (albeit a small one in my opinion) I see here is that you can minimize the number of requests sent to Google).
"Automatically" - do a GET on Google's endpoint to verify this token
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
Using a Google API Client Library - like the official one.
Here's how this could look:
private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}";
public ProviderUserDetails GetUserDetails(string providerToken)
{
var httpClient = new MonitoredHttpClient();
var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken));
HttpResponseMessage httpResponseMessage;
try
{
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
}
catch (Exception ex)
{
return null;
}
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
return null;
}
var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response);
if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud))
{
Log.WarnFormat("Google API Token Info aud field ({0}) not containing the required client id", googleApiTokenInfo.aud);
return null;
}
return new ProviderUserDetails
{
Email = googleApiTokenInfo.email,
FirstName = googleApiTokenInfo.given_name,
LastName = googleApiTokenInfo.family_name,
Locale = googleApiTokenInfo.locale,
Name = googleApiTokenInfo.name,
ProviderUserId = googleApiTokenInfo.sub
};
}
Related
I've probably made a really silly mistake, I am able to make a successful POST request to server. I am also able to get a response from server 201 as well as being able to view the json("requestid"). I am able to deserialize the JSON and parse requestid as a string (public string requestID). I have a timer (timer1) set up to poll the server every 1 second, the polling should start successfully if 201 created and does. However the problem I am having is that it does not include the requestid. Would someone be able to advise and tell me where I had gone wrong please?
namespace RestAPI
{
public enum httpVerb
{
GET,
POST,
PUT,
DELETE
}
class RESTAPI
{
public string endPoint { get; set; }
public httpVerb httpMethod { get; set; }
public string userPassword { get; set; }
public int sendAmount { get; set; }
public string location { get; set; }
public string requestId { get; set; }
public RESTAPI()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
userPassword = string.Empty;
//requestId = string.Empty;
}
public string makeRequest()
{
string strResponseValue = string.Empty;
string result = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
request.ContentType = "application/json";
request.Accept = "application/connect.v1+json";
String username = "mokhan";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + userPassword));
request.Headers.Add("Authorization", "Basic " + encoded);
if(httpMethod == httpVerb.POST)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"transactionType\":\"SALE\"," + "\"amount\":" + sendAmount + "," +
"\"currency\":\"GBP\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse responseback = (HttpWebResponse)request.GetResponse();
//string result;
using (StreamReader rdr = new StreamReader(responseback.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
if (responseback.StatusCode == HttpStatusCode.Created)
{
dynamic jsonObj = JsonConvert.DeserializeObject(result);
requestId = jsonObj.requestId.ToString();
return requestId;
}
return result;
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
}
finally
{
if (response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
This code below shows my POST and GET requests to server, I have added the timer method to start in my POST request after I get a response and have added the code for polling in my timer method. I have also set string transactionid = rclient.requestId; and the called on rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions/" + transactionid; to poll the server every 1 second but for some reason it's not picking up transactionid.
namespace RestAPI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void go_Click(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text;
rclient.userPassword = txtbox2.Text;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
}
private void debugOutput(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtBoxResponse.Text = txtBoxResponse.Text + strDebugText + Environment.NewLine;
txtBoxResponse.SelectionStart = txtBoxResponse.TextLength;
txtBoxResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void txtBox_TextChanged(object sender, EventArgs e)
{
}
private void Test_Click(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.httpMethod = httpVerb.POST;
rclient.sendAmount = Convert.ToInt32(amount.Text);
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions";
rclient.userPassword = txtbox2.Text;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
timer1.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.httpMethod = httpVerb.GET;
string transactionid = rclient.requestId;
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions/" + transactionid;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
}
}
}
Just solved the issue, in my public class RESTAPI, i un-commented this
//requestId = string.Empty;
once done, i was able to pick up the request ID as a string and then call it in my timer
string transactionid = rclient.requestId;
I am struggling with web requests to some websites like (mrporter.com or size.co.uk). Outside USA (so no USA IPs), I can make requests just fine. However once I am behind USA IP, requests either time out or end up with "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" exception. I have tried all kind of headers combinations, still no luck. I need to note, that those websites are opening in browsers just fine.
This is my implementation that works with non-USA ips.
var _request = (HttpWebRequest)WebRequest.Create("https://www.mrporter.com");
_request.CookieContainer = new CookieContainer();
_request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
_request.KeepAlive = true;
_request.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
_request.Headers.Add("Accept-Encoding", "gzip, deflate");
_request.Headers.Add("Accept-Language", "en-GB, en-US; q=0.9, en; q=0.8");
_request.Headers.Add("Upgrade-Insecure-Requests", "1");
var _srr = "";
using (var response = _request.GetResponse())
{
var httpWebResponse = response.GetResponseStream();
using (var sr = new StreamReader(httpWebResponse))
{
_srr = sr.ReadToEnd();
}
}
Anybody can help? I seriously wasted hours with it with no result ...
This is the procedure used test the Server you mentioned (https://www.mrporter.com/)
The main method can be called this way:
(The StreamObject class returns a number of informations about the Server, including the Html of the landing page. (Also its Cookies, IP Address etc.)
public async void SomeMethodAsync()
{
StreamObject _streamObj = new StreamObject()
{
ResourceURI = new Uri(#"https://www.mrporter.com/"),
ProcessStream = true
};
_streamObj = await HTTP_GetStreamAsync(_streamObj);
}
I had to cut out the Proxy setup (it's inititialized if needed in the same method that initializes the WebRequest Headers). Anyway, it should looks like this:
if ([UseProxy])
if ([ProxyHost] != null) {
WebRequest.Proxy = new WebProxy([ProxyHost], [ProxyPort]);
if ([Credentials] != null)
WebRequest.Proxy.Credentials = new NetworkCredential([Credentials].UserID, [Credentials].Password);
} else {
WebRequest.Proxy = WebRequest.GetSystemWebProxy();
}
}
If you plan on using a Proxy, you should also insert this parameter in
your app.config file:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
When the main method (HTTP_GetStreamAsync()) returns, StreamObject.Payload will contain the decoded Html Page of the Site you connected to.
There are a number of sub-utilities and it might look complicated, but everything should work fine. You just need to insert all of the code inside a class and modify the calling method (SomeMethodAsync()) accordingly.
(I'll edit this when I have a moment).
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
private const uint COR_E_INVALIDOPERATION = 0x80131509;
public class StreamObject
{
public Stream ContentStream { get; set; }
public bool ProcessStream { get; set; }
public Uri ResourceURI { get; set; }
public Uri ResponseURI { get; set; }
public string Referer { get; set; }
public string Payload { get; set; }
public string ServerType { get; set; }
public string ServerName { get; set; }
public IPAddress[] ServerIP { get; set; }
public string ContentName { get; set; }
public string ContentType { get; set; }
public string ContentCharSet { get; set; }
public string ContentLanguage { get; set; }
public long ContentLenght { get; set; }
public HttpStatusCode StatusCode { get; set; }
public string StatusDescription { get; set; }
public WebExceptionStatus WebException { get; set; }
public string WebExceptionDescription { get; set; }
public CookieContainer Cookies { get; set; }
}
public async Task<StreamObject> HTTP_GetStreamAsync(StreamObject RequestObject)
{
if (string.IsNullOrEmpty(RequestObject.ResourceURI.ToString().Trim()))
return null;
MemoryStream _memstream = new MemoryStream();
HttpWebRequest httpRequest;
CookieContainer _cookiejar = new CookieContainer();
HttpStatusCode _StatusCode = HttpStatusCode.OK;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += TlsValidationCallback;
if (RequestObject.Cookies != null && RequestObject.Cookies.Count > 0)
_cookiejar = RequestObject.Cookies;
httpRequest = WebRequest.CreateHttp(RequestObject.ResourceURI);
try
{
HTTP_RequestHeadersInit(ref httpRequest, _cookiejar, null);
httpRequest.Referer = RequestObject.Referer;
using (HttpWebResponse httpResponse = (HttpWebResponse)await httpRequest.GetResponseAsync())
{
Stream ResponseStream = httpResponse.GetResponseStream();
if (_StatusCode == HttpStatusCode.OK)
{
await ResponseStream.CopyToAsync(_memstream);
RequestObject.ContentStream = _memstream;
RequestObject.ResponseURI = httpResponse.ResponseUri;
RequestObject.ContentLenght = _memstream.Length;
RequestObject.ContentCharSet = httpResponse.CharacterSet ?? string.Empty;
RequestObject.ContentLanguage = httpResponse.Headers["Content-Language"] ?? string.Empty;
RequestObject.ContentType = httpResponse.ContentType.ToLower();
if (RequestObject.ContentType.IndexOf(#"/") > -1)
{
do
{
RequestObject.ContentType = RequestObject.ContentType.Substring(RequestObject.ContentType.IndexOf(#"/") + 1);
if (RequestObject.ContentType.IndexOf(#"/") < 0)
break;
} while (true);
if (RequestObject.ContentType.IndexOf(";") > -1)
RequestObject.ContentType = RequestObject.ContentType.Substring(0, RequestObject.ContentType.IndexOf(#";"));
RequestObject.ContentType = "." + RequestObject.ContentType;
}
RequestObject.ContentName = httpResponse.Headers["Content-Disposition"] ?? string.Empty;
if (RequestObject.ContentName.Length == 0)
RequestObject.ContentName = RequestObject.ResourceURI.Segments.Last();
RequestObject.ServerType = httpResponse.Server;
RequestObject.ServerName = RequestObject.ResponseURI.DnsSafeHost;
RequestObject.ServerIP = await Dns.GetHostAddressesAsync(RequestObject.ServerName);
RequestObject.StatusCode = _StatusCode;
RequestObject.StatusDescription = httpResponse.StatusDescription;
if (RequestObject.ProcessStream)
RequestObject.Payload = ProcessResponse(RequestObject.ContentStream,
Encoding.GetEncoding(RequestObject.ContentCharSet),
httpResponse.ContentEncoding);
}
}
}
catch (WebException exW)
{
if (exW.Response != null)
{
RequestObject.StatusCode = ((HttpWebResponse)exW.Response).StatusCode;
RequestObject.StatusDescription = ((HttpWebResponse)exW.Response).StatusDescription;
}
RequestObject.WebException = exW.Status;
RequestObject.WebExceptionDescription = exW.Message;
}
catch (System.Exception exS)
{
if ((uint)exS.HResult == COR_E_INVALIDOPERATION)
{
RequestObject.WebException = await PingHostAddressAsync("8.8.8.8", 500) > 0
? WebExceptionStatus.NameResolutionFailure
: WebExceptionStatus.ConnectFailure;
RequestObject.WebExceptionDescription = RequestObject.WebException.ToString();
}
else
{
RequestObject.WebException = WebExceptionStatus.RequestCanceled;
RequestObject.WebExceptionDescription = RequestObject.WebException.ToString();
}
}
finally
{
ServicePointManager.ServerCertificateValidationCallback -= TlsValidationCallback;
}
RequestObject.Cookies = httpRequest.CookieContainer;
RequestObject.StatusCode = _StatusCode;
return RequestObject;
} //HTTP_GetStream
private bool TlsValidationCallback(object sender, X509Certificate CACert, X509Chain CAChain, SslPolicyErrors sslPolicyErrors)
{
X509Certificate2 _Certificate = new X509Certificate2(CACert);
//ADD A CERIFICATE HERE IF NEEDED
//X509Certificate2 _CACert = new X509Certificate2(#"[localstorage]/ca.cert");
//CAChain.ChainPolicy.ExtraStore.Add(_CACert);
X509Certificate2 cert = (X509Certificate2)CACert;
CAChain.Build(_Certificate);
foreach (X509ChainStatus CACStatus in CAChain.ChainStatus)
{
if ((CACStatus.Status != X509ChainStatusFlags.NoError) &
(CACStatus.Status != X509ChainStatusFlags.UntrustedRoot))
return false;
}
return true;
}
private void HTTP_RequestHeadersInit(ref HttpWebRequest _httpreq, CookieContainer _cookiecontainer, StreamObject sObject)
{
_httpreq.Date = DateTime.Now;
_httpreq.Timeout = 30000;
_httpreq.ReadWriteTimeout = 30000;
_httpreq.CookieContainer = _cookiecontainer;
_httpreq.KeepAlive = true;
_httpreq.ConnectionGroupName = Guid.NewGuid().ToString();
_httpreq.AllowAutoRedirect = true;
_httpreq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
_httpreq.ServicePoint.MaxIdleTime = 30000;
_httpreq.ServicePoint.Expect100Continue = false;
_httpreq.Referer = sObject.Referer ?? string.Empty;
_httpreq.UserAgent = "Mozilla/5.0 (Windows NT 10; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
_httpreq.Accept = "ext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_httpreq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en-GB;q=0.5,en;q=0.3");
_httpreq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8");
_httpreq.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
//I had to cut out the WebRequest Proxy setup here
}
private string ProcessResponse(Stream stream, Encoding encoding, string ContentEncoding)
{
string html = string.Empty;
stream.Position = 0;
try
{
using (MemoryStream _memStream = new MemoryStream())
{
if (ContentEncoding.Contains("gzip"))
{
using (GZipStream _gzipStream = new GZipStream(stream, System.IO.Compression.CompressionMode.Decompress))
{
_gzipStream.CopyTo(_memStream);
};
}
else if (ContentEncoding.Contains("deflate"))
{
using (DeflateStream _deflStream = new DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress))
{
_deflStream.CopyTo(_memStream);
};
}
else
{
stream.CopyTo(_memStream);
}
_memStream.Position = 0;
using (StreamReader _reader = new StreamReader(_memStream, encoding))
{
html = _reader.ReadToEnd().Trim();
html = DecodeMetaCharSetEncoding(_memStream, html, encoding);
};
};
}
catch (Exception)
{
return string.Empty;
}
return html;
}
private string DecodeMetaCharSetEncoding(Stream memStream, string _html, Encoding _encode)
{
Match _match = new Regex("<meta\\s+.*?charset\\s*=\\s*\"?(?<charset>[A-Za-z0-9_-]+)\"?",
RegexOptions.Singleline |
RegexOptions.IgnoreCase).Match(_html);
if (_match.Success)
{
string charset = _match.Groups["charset"].Value.ToLower() ?? "utf-8";
if ((charset == "unicode") | (charset == "utf-7") | (charset == "utf-16"))
charset = "utf-8";
try
{
Encoding metaEncoding = Encoding.GetEncoding(charset);
if (_encode.WebName != metaEncoding.WebName)
{
memStream.Position = 0L;
using (StreamReader recodeReader = new StreamReader(memStream, metaEncoding))
{ _html = recodeReader.ReadToEnd().Trim(); }
}
}
catch (ArgumentException)
{
_html = string.Empty;
}
catch (Exception)
{
_html = string.Empty;
}
}
return _html;
}
public async Task<IPStatus> PingHostAddressAsync(string HostAddress, int timeout)
{
if (string.IsNullOrEmpty(HostAddress.Trim()))
return IPStatus.BadDestination;
byte[] buffer = new byte[32];
PingReply iReplay = null;
IPStatus ipStatus;
using (Ping iPing = new Ping())
{
try
{
IPAddress _IPAddress = IPAddress.Parse(HostAddress);
iReplay = await iPing.SendPingAsync(_IPAddress, timeout, buffer, new PingOptions(64, false));
return iReplay.Status;
}
catch (FormatException)
{
return IPStatus.BadDestination;
}
catch (NotSupportedException nsex)
{
ipStatus = (IPStatus)nsex.HResult;
ipStatus = IPStatus.DestinationProtocolUnreachable;
}
catch (PingException pex)
{
ipStatus = (IPStatus)pex.HResult;
}
catch (SocketException soex)
{
ipStatus = (IPStatus)soex.HResult;
}
catch (Exception ex)
{
//Log ex
ipStatus = (IPStatus)ex.HResult;
}
return (iReplay != null) ? iReplay.Status : ipStatus;
}
}
I can get accesstoken but I don't know how to get username and uuid from accesstoken, when I login it's gave me something like that
{"accessToken":"123","clientToken":"123","selectedProfile":{"id":"123","name":"playername"},"availableProfiles":[{"id":"123","name":"playername"}]}
Thanks!
private vstrong textoid Signin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
try
{
bool isSignedIn = false;
if (isSignedIn == true)
{
var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/invalidate");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
accessToken = Settings.Default.accessToken,
clientToken = Settings.Default.clientToken
});
}
Settings.Default.UUID = null;
Settings.Default.accessToken = null;
Settings.Default.clientToken = null;
}
else
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
agent = new
{
name = "Minecraft",
version = 1
},
username = email.Text,
password = password.Password
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
ACCESS_TOKEN = result;
}
}
}
catch (WebException)
{
MessageBox.Show("Login failed. Invalid username or password.");
}
}
string ACCESS_TOKEN;
public string GetAccessToken()
{
return ACCESS_TOKEN;
}
That is a JSON response, which you will need to deserialize to use most effectively. You can do this with the following code:
var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(result);
Now, the MinecraftLoginResponse will need to be a class you create yourself, unless there is a library that you are using for this. JSON consists of variable value combinations, the values after the ':', separated by commas. {} denote an object, and [] a collection.
In the minecraft response, you have two objects; the response itself, and then the Profile object. C# code of this response is:
public class Profile
{
public string id { get; set; }
public string name { get; set; }
}
public class LoginResponse
{
public string accessToken { get; set; }
public string clientToken { get; set; }
public Profile selectedProfile { get; set; }
public List<Profile> availableProfiles { get; set; }
}
I made the above by running the example response through this website, then removing the SelectedProfile and AvailableProfile as these are, logically, going to be the same thing. (Selected will be one of the available profiles).
I am trying to send a request from server side to my API, here is my code from Server
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:59606/api/values/UserCheck");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"username\":\"User\"," +
"\"password\":\"Mypassword\"," +
"\"logonfrom\":\"DOMAIN\\DomainName\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
May API code are below:
[HttpPost]
[ActionName("UserCheck")]
public bool UserCheck([FromBody]User value)
{
ContextType CT = ContextType.Domain;
if (value.logonfrom.Split('\\')[0] == "DOMAIN")
{
CT = ContextType.Domain;
}else if(value.logonfrom.Split('\\')[0] == "MACHINE")
{
CT = ContextType.Machine;
}else
{
return false;
}
return CheckCredentials(value.username, value.password, CT,value.logonfrom.Split('\\')[1]);
}
when my request reach the Action of UserCheck, the value of
([FromBody]User value)
is null
my Class for the User is below
public class User
{
public string username { get; set; }
public string password { get; set; }
public string system { get; set; }
public string IP { get; set; }
public string logonfrom { get; set; }
}
BUT once i remove the logonfrom variable from json there is no error, i mean the parameter (value) successfully captures the content i sent.
Thanks
use the following peace of code.
string json = JsonConvert.SerializeObject(new { username = "afsa", password = "fsaf", system = "fsaf", ip = "fsf", logonfrom ="fsfsd"});
I am using this code to login with google. And trying to get user details.
else if (Session["loginTo"].ToString() == "google")
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string codeg = words[1];
if (codeg != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + codeg + "&client_id=" + ggl_app_key + "&client_secret=" + ggl_app_secret + "&redirect_uri=" + ggl_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);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
//getgoogleplususerdataSer(accessToken);
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
getgoogleplususerdataSer(accessToken);
}
}
}
}
}
}
}
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
// You will get the user information here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
}
}
I have written this code on my master page. But getting error at method call 'getgoogleplususerdataSer(accessToken);' error is "An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%# Page Async="true" %>"