MediaWiki API login: "Unable to continue login. Your session most likely timed out." - webforms

Trying to create an invite only wiki, that we can login to with a bot account once the customer has authenticated using our own webpage on our corporate website.
I've been using the documentation from here:
https://www.mediawiki.org/wiki/API:Login
Anyway I can get a success response from the API sandbox, but the POST from our new API interface webpage errors with "Unable to continue login. Your session most likely timed out."
I get the same message even if I deliberately enter invalid login credentials, so I would imagine it's not getting as far as actually checking the username/password/token. It's really annoying that there's no decent error to work from.
GETting a token via action=query works fine from the same webpage.
Our webpage is a web forms page written in VB (I know).
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("https://tmsinsight.com/TMSWiki/api.php?action=query&meta=tokens&type=login&format=json")
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(result)
Dim LoginToken As String = j("query")("tokens")("logintoken")
Response.Write(LoginToken & "<br/>")
webClient.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
Dim parameters = New NameValueCollection()
parameters.Add("action", "login")
parameters.Add("format", "json")
parameters.Add("lgname", "botusername#botusername")
parameters.Add("lgpassword", "botpassword")
parameters.Add("lgtoken", LoginToken)
Dim responsebytes = webClient.UploadValues("https://tmsinsight.com/TMSWiki/api.php", "POST", parameters)
Dim resultRequest = Encoding.UTF8.GetString(responsebytes)
Response.Write(resultRequest)

Related

Paypal Invoice SDK Service Call + Express Checkout + Recurrying Payment issue

Hi I have implemented Paypal Invoice, Express Checkout & Recurring Payments services using adaptive methods (NVP) call. It is working fine on my local system with sandbox account but not on development server and facing problem wherever I have called the paypal services based on request.
Code
InvoiceModelAlias.PaymentTermsType paymentTermsType = (InvoiceModelAlias.PaymentTermsType)Enum.Parse(typeof(InvoiceModelAlias.PaymentTermsType),invoice.PaymentTerms.ToUpper());
InvoiceModelAlias.CreateAndSendInvoiceRequest invoiceRequest = new InvoiceModelAlias.CreateAndSendInvoiceRequest();
invoiceRequest.requestEnvelope = new InvoiceModelAlias.RequestEnvelope();
invoiceRequest.requestEnvelope.errorLanguage = "en_US";
invoiceRequest.invoice = new InvoiceModelAlias.InvoiceType();
invoiceRequest.invoice.currencyCode = invoice.CurrencyCode;
invoiceRequest.invoice.merchantEmail = invoice.MerchantEmail;
invoiceRequest.invoice.payerEmail = invoice.PayerEmail;
invoiceRequest.invoice.paymentTerms = paymentTermsType;
invoiceRequest.invoice.itemList = new InvoiceModelAlias.InvoiceItemListType();
invoiceRequest.invoice.itemList.item = new List<InvoiceModelAlias.InvoiceItemType>();
invoiceRequest.invoice.itemList.item.Add(new InvoiceModelAlias.InvoiceItemType(invoice.ItemName, Convert.ToDecimal(invoice.ItemQuantity), Convert.ToDecimal(invoice.ItemAmount)));
InvoiceAlias.InvoiceService invoiceService;
InvoiceModelAlias.CreateAndSendInvoiceResponse invoiceResponse = null;
invoiceService = GetService();
invoiceResponse = invoiceService.CreateAndSendInvoice(invoiceRequest);
string ackRsponse = invoiceResponse.responseEnvelope.ack.ToString();
invoiceService.CreateAndSendInvoice(invoiceRequest)
Exception
PayPal.Exception.ConnectionException: Invalid HTTP response The underlying connection was closed: An unexpected error occurred on a receive.
at PayPal.HttpConnection.Execute(String payLoad, HttpWebRequest httpRequest)
at PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.Invoice.InvoiceService.CreateAndSendInvoice(CreateAndSendInvoiceRequest createAndSendInvoiceRequest, String apiUserName)
at PayPal.Invoice.InvoiceService.CreateAndSendInvoice(CreateAndSendInvoiceRequest createAndSendInvoiceRequest)
at DoPayments.Payments.Invoices.CreateAndSendInvoice(Invoice invoice)
Will you please someone help me to get this out or suggest whats the reason behind this as it is working fine at local but not on development/production server.
Same kind of issue I am facing in case of express checkout and recurring payment methods too which is below:
com.paypal.sdk.exceptions.FatalException: The underlying connection was closed: An unexpected error occurred on a receive.
at com.paypal.sdk.core.nvp.NVPAPICaller.Call(String NvpRequest)
at com.paypal.sdk.services.NVPCallerServices.Call(String requestnvp)
Thanks in advance.

How to Get OAuth Access Token for Pinterest?

I am accessing Pinterest API for getting user's information by using this url but I can not find that how to generate an access token for Pinterest.
According to this blog post, it says that
Pinterest uses OAuth2 to authenticate users
Can you please tell me, from where I can generate OAuth access tokens for Pinterest?
First, register for an app and set up a redirect URI:
https://developers.pinterest.com/manage/
Then, find your client secret under Signature Tester:
https://developers.pinterest.com/tools/signature/
Bring the user to the OAuth dialog like this:
https://www.pinterest.com/oauth/?consumer_id=[client_id]&response_type=[code_or_token]&scope=[list_of_scopes]
If response type if token, it will be appended as a hash in the redirect URI.
If response type is code, see the post below for details on how to exchange code for token:
What's the auth code endpoint in Pinterest?
You need to register a client app under manager Apps option in Dropdown menu when you login
or
https://developers.pinterest.com/manage/
Register your app and you get AppID.
This follow the process in this link you have
http://wiki.gic.mx/pinterest-developers/
Hope this helps
**USING C#**
public string GetOAuthToken(string data)
{
string strResult = string.Empty;
try
{
string Clientid = WebConfigurationManager.AppSettings["Pinterest_Clientid"];
string ClientSecret = WebConfigurationManager.AppSettings["Pinterest_ClientSecret"];
string uri_token = WebConfigurationManager.AppSettings["Pinterest_Uri_Token"];
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri_token);
string parameters = "grant_type=authorization_code"
+ "&client_id="
+ Clientid
+ "&client_secret="
+ ClientSecret
+ "&code="
+ data;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
System.IO.Stream os = null;
req.ContentLength = bytes.Length;
os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
System.Net.WebResponse webResponse = req.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string response = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(response);
strResult = "SUCCESS:" + o["access_token"].ToString();
}
catch (Exception ex)
{
strResult = "ERROR:" + ex.Message.ToString();
}
return strResult;
}
Refer
Pinterest uses the User Flow or Oauth2
When you have an app you ant to use the app flow with an access token
So you need to create the flow yourself or use this tool online
https://frederik.today/codehelper/tools/oauth-access-token-pinterest
To make it yourself
Request Token
Exchange code for Acces Token
https://developers.pinterest.com/docs/api/v5/

Windows Authentication With WMI

I want to use Windows current credential when using WMI to query data on a remote machine, but in many examples I found that I have to use Connection object which needs you to provide a username, password and authority for validating username and password as shown below:
Dim connection As New ConnectionOptions
connection.Username = userNameBox.Text
connection.Password = passwordBox.Text
connection.Authority = "ntlmdomain:MyDomain"
Dim scope As New ManagementScope( _
"\\RemoteMachine\root\CIMV2", connection)
scope.Connect()
I want to bypass these inputs and use current Windows logon credentials instead, is there any way for this?
Here' the C# example with connnection options using Windows credentials.
ConnectionOptions connectionOptions = new ConnectionOptions
{
Authentication = AuthenticationLevel.PacketPrivacy,
Impersonation = ImpersonationLevel.Impersonate
};

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

dotnetopenauth asp.net mvc2 project template - broken when running from localhost:xxxx

So I create a new dnoa mvc2 site from the template, run setup.aspx without issue, login and authorize my openid - all ok, but on the redirect to
http://localhost:18916/Auth/PopUpReturnTo?dnoa.uipopup=1&dnoa.popupUISupported=1&index=0&dnoa.userSuppliedIdentifier=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid&dnoa.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&dnoa.claimed_id=&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2010-07-24T18%3A06%3A36ZcustWWIY5CfXTQ&openid.return_to=http%3A%2F%2Flocalhost%3A18916%2FAuth%2FPopUpReturnTo%3Fdnoa.uipopup%3D1%26dnoa.popupUISupported%3D1%26index%3D0%26dnoa.userSuppliedIdentifier%3Dhttps%253A%252F%252Fwww.google.com%252Faccounts%252Fo8%252Fid%26dnoa.op_endpoint%3Dhttps%253A%252F%252Fwww.google.com%252Faccounts%252Fo8%252Fud%26dnoa.claimed_id%3D&openid.assoc_handle=AOQobUdkpLPAPC1LRQKPaQcy2UlG8R4pjWmpDCSV_1odtA33o_HfNleiMi9ZjX8RU-kIIJnJ&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle%2Cns.ext1%2Cext1.mode%2Cext1.type.alias3%2Cext1.value.alias3%2Cext1.type.alias1%2Cext1.value.alias1&openid.sig=zkBfpugK7xT0da49hZLNQZz4Xn83UiZB%2BhEHz6B37Cw%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawk3FGqct35R7wya-0Bkq-0_Qnc1AB-YSw4&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawk3FGqct35R7wya-0Bkq-0_Qnc1AB-YSw4&openid.ns.ext1=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.ext1.mode=fetch_response&openid.ext1.type.alias3=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&openid.ext1.value.alias3=sky.sanders%40gmail.com&openid.ext1.type.alias1=http%3A%2F%2Faxschema.org%2Fcontact%2Femail&openid.ext1.value.alias1=sky.sanders%40gmail.com&openid.ns.ext2=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fui%2F1.0&openid.ext2.mode=popup
all i get is an alert [object Error].
The 'getting started' says that all I have to do is get the database set up and I would be good to go.
This does not seem good to go. If there are other criteria to getting the sample working they should be declared.
In any case, what is required to get this running on localhost:xxx (cassini/cassinidev)?
What you're seeing is due to a bug in IE8 having to do with crossing trust zones (from Local Computer/Intranet to Internet Zone). If you use a non-IE browser it will work. When you publish your web site on the Internet, IE8 will work fine because it doesn't cross into the Intranet zone during login.
I'm using that method you gave me before for my authentication, and here is my Controller Authentication Code
<ValidateInput(False)> _
Public Function Authenticate(ByVal returnUrl As String) As ActionResult
Dim response = openid.GetResponse()
If response Is Nothing Then
' Stage 2: user submitting Identifier
Dim id As Identifier
If Identifier.TryParse(Request.Form("openid_identifier"), id) Then
Try
Return openid.CreateRequest(Request.Form("openid_identifier")).RedirectingResponse.AsActionResult()
Catch ex As ProtocolException
ViewData("Message") = ex.Message
Return View("Login")
End Try
Else
ViewData("Message") = "Invalid identifier"
Return View("Login")
End If
Else
' Stage 3: OpenID Provider sending assertion response
Select Case response.Status
Case AuthenticationStatus.Authenticated
If Not OpenIDService.IsOpenIdAssociated(response.ClaimedIdentifier) Then
UserService.AddUser(response.ClaimedIdentifier, response.FriendlyIdentifierForDisplay)
UserService.SubmitChanges()
ActivityLogService.AddActivity(OpenIDService.GetOpenId(response.ClaimedIdentifier).UserID, _
Utilities.ActivityLog.LogType.UserAdded, _
HttpContext.Request.UserHostAddress)
Else
ActivityLogService.AddActivity(OpenIDService.GetOpenId(response.ClaimedIdentifier).UserID, _
Utilities.ActivityLog.LogType.UserLogin, _
HttpContext.Request.UserHostAddress)
End If
ActivityLogService.SubmitChanges()
' Create the authentication cookie. This cookie
' includes the AuthUserData information in the
' userData field of the FormsAuthentication Cookie.
Dim authUser As Authentication.AuthUserData = New Authentication.AuthUserData(OpenIDService.GetOpenId(response.ClaimedIdentifier).User)
HttpContext.Response.Cookies.Add(Authentication.CustomAuthentication.CreateAuthCookie(response.ClaimedIdentifier, _
authUser, _
True))
authUser = Nothing
If Not String.IsNullOrEmpty(returnUrl) Then : Return Redirect(returnUrl)
Else : Return RedirectToAction("Index", "Events")
End If
Case AuthenticationStatus.Canceled
ViewData("Message") = "Canceled at provider"
Return View("Login")
Case AuthenticationStatus.Failed
ViewData("Message") = response.Exception.Message
Return View("Login")
End Select
End If
Return New EmptyResult()
End Function
I have a custom table in my database called Users and I also have an OpenIDs table with a UserID field. The OpenIds table allows me to have an unlimited number of OpenIds per user.
All of this works both locally for me as well as on the production server and staging server.

Resources