PKCE flow Error code: 500 code challenge required - xero-api

I'm trying to get the PKCE example to work, but I keep hitting
Error code: 500
Error: invalid_request : code challenge required
Here's a sample url, it does include a code_challenge param generated with the example code.
https://login.xero.com/identity/connect/authorize
?client_id=XXX
&response_type=code
&scope=openid%20profile%20email%20offline_access%20files%20accounting.transactions%20accounting.contacts&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2F
&code_challenge=tj6n3SLd6FZ8g6jjSJYvfC--4r2PHGnpbSGTwIreNqQ
&code_challenge_method=S256
The registered app is a PKCE flow, kind of out of options what it could be.
Here's the code I use, the only changes are the last 2 lines where I launch the browser a I'm connecting from a desktop app. Tried pasting the generated url into the browser directly but that also didn't work.
XeroConfiguration xconfig = new XeroConfiguration();
xconfig.ClientId = "XXX";
xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
//xconfig.State = "YOUR_STATE"
var client = new XeroClient(xconfig);
// generate a random codeVerifier
var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
Random random = new Random();
int charsLength = random.Next(43, 128);
char[] randomChars = new char[charsLength];
for (int i = 0; i < charsLength; i++) {
randomChars[i] = validChars[random.Next(0, validChars.Length)];
}
string codeVerifier = new String(randomChars);
var uri = client.BuildLoginUriPkce(codeVerifier);
Clipboard.SetText(uri);
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");

Related

Pentaho - upload file using API

I need to upload a file using an API.
I tried REST CLIENT and didn't find any options.
Tried with HTTP POST and that responded with 415.
Please suggest how to accomplish this
Error 415 is “Unsupported media type”.
You may need to change the media type of the request or check whether that type of file us accepted by the remote server.
https://en.m.wikipedia.org/wiki/List_of_HTTP_status_codes
This solution uses only standard classes of jre 7. Add a step Modified Java Script Value in your transformation. You will have to add two columns in the flow: URL_FORM_POST_MULTIPART_COLUMN and FILE_URL_COLUMN, you can add as many files as you want, you will just have to call outputStreamToRequestBody.write more times.
try
{
//in this step you will need to add two columns from the previous flow -> URL_FORM_POST_MULTIPART_COLUMN, FILE_URL_COLUMN
var serverUrl = new java.net.URL(URL_FORM_POST_MULTIPART_COLUMN);
var boundaryString = "999aaa000zzz09za";
var openBoundary = java.lang.String.format("\n\n--%s\nContent-Disposition: form-data\nContent-Type: text/xml\n\n" , boundaryString);
var closeBoundary = java.lang.String.format("\n\n--%s--\n", boundaryString);
// var netIPSocketAddress = java.net.InetSocketAddress("127.0.0.1", 8888);
// var proxy = java.net.Proxy(java.net.Proxy.Type.HTTP , netIPSocketAddress);
// var urlConnection = serverUrl.openConnection(proxy);
var urlConnection = serverUrl.openConnection();
urlConnection.setDoOutput(true); // Indicate that we want to write to the HTTP request body
urlConnection.setRequestMethod("POST");
//urlConnection.addRequestProperty("Authorization", "Basic " + Authorization);
urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
var outputStreamToRequestBody = urlConnection.getOutputStream();
outputStreamToRequestBody.write(openBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
outputStreamToRequestBody.write(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(FILE_URL_COLUMN)));
outputStreamToRequestBody.write(closeBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
outputStreamToRequestBody.flush();
var httpResponseReader = new java.io.BufferedReader(new java.io.InputStreamReader(urlConnection.getInputStream()));
var lineRead = "";
var finalText = "";
while((lineRead = httpResponseReader.readLine()) != null) {
finalText += lineRead;
}
var status = urlConnection.getResponseCode();
var result = finalText;
var time = new Date();
}
catch(e)
{
Alert(e);
}
I solved this by using the solution from http://www.dietz-solutions.com/2017/06/pentaho-data-integration-multi-part.html
Thanks Ben.
He's written a Java class for Multi-part Form submission. I extendd by adding a header for Authorization...

Error when changing password in AD LDS

I have problem when implemented password updating of user in AD LDS: it throws below error when calling connection.Modify().
Does anybody have experience with ADLDS and its errors?
Operations Error:00002077: SvcErr: DSID-03380736, problem 5012 (DIR_ERROR), data 8237
Code as below:
var entry = GetUserEntry(userName, AttributeList(AttributeTypes.Basic));
//create the ldap modifications
var modifications = new LdapModification[2];
var deletePassword = new LdapAttribute(application.UserPasswordAttribute, oldPassword);
modifications[0] = new LdapModification(LdapModification.DELETE, deletePassword);
var addPassword = new LdapAttribute(application.UserPasswordAttribute, newPassword);
modifications[1] = new LdapModification(LdapModification.ADD, addPassword);
//perform the modification
connection.Modify(entry.DN, modifications);
The entry.DN includes: "CN=user1,CN=Users,CN=sampleInstance,DC=local,DC=com".
By the way, I'm using SSL connection.

EchoSign: Extra signature box appears while sending out to multiple signers

I'm trying to create an url widget using below code to allow the document be signed by multiple signers. But when I upload the document, an extra signature box appears at the beginning, then the remaining signature boxes appear for each email address I mention in the WidgetCreationInfo.CounterSigners property. I need to remove the extra signature box from the document.
var senderInfo = new com.echosign.secure22.SenderInfo();
senderInfo.email = "abx#xyz.com";
senderInfo.password = "******";
var widgetInfo = new com.echosign.secure22.WidgetCreationInfo();
widgetInfo.name = "test widget";
widgetInfo.fileInfos = new EchoSign.com.echosign.secure22.FileInfo[1];
widgetInfo.fileInfos[0] = new EchoSign.com.echosign.secure22.FileInfo();
widgetInfo.fileInfos[0].file = System.IO.File.ReadAllBytes(fileName);
widgetInfo.fileInfos[0].fileName = System.IO.Path.GetFileName(fileName);
widgetInfo.callbackInfo = new com.echosign.secure22.CallbackInfo();
widgetInfo.callbackInfo.signedDocumentUrl = redirectUrl;
widgetInfo.signatureFlow = EchoSign.com.echosign.secure22.SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED;
widgetInfo.counterSigners = new com.echosign.secure22.RecipientInfo[2];
widgetInfo.counterSigners[0] = new com.echosign.secure22.RecipientInfo();
widgetInfo.counterSigners[0].email = "abc#gmail.com";
widgetInfo.counterSigners[0].role = com.echosign.secure22.RecipientRole.SIGNER;
widgetInfo.counterSigners[0].roleSpecified = true;
widgetInfo.counterSigners[1] = new com.echosign.secure22.RecipientInfo();
widgetInfo.counterSigners[1].email = "xyz#yahoo.com";
widgetInfo.counterSigners[1].role = com.echosign.secure22.RecipientRole.SIGNER;
widgetInfo.counterSigners[1].roleSpecified = true;
var result = ES22.createEmbeddedWidget(apiKey, senderInfo, widgetInfo);
Can anyone please help?
The first signature block is for the widget signer. The rest of the recipients you have added are counter signers and would need to sign once the first signer of the widget signs. If you simply need a document to be signed by multiple signers, you can create a normal agreement instead of a widget. If yow want to host the signing page, you can use eSign services API to retrieve the signing URL of the signers in the agreement. Let me know if this helps.

How to insert rule in Google Calendar ACL from Google Apps Script

How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).
//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
// Get Calendar ID, script user's email, and the API Key for access to Calendar API
var calId = '12345calendar.google.com';
var userEmail = Session.getActiveUser().getEmail();
var API_KEY = 'ABC123';
var newUserEmail = 'person#example.net';
// Get authorization to access the Google Calendar API
var apiName = 'calendar';
var scope = 'https://www.googleapis.com/auth/calendar';
var fetchArgs = googleOAuth_(apiName, scope);
fetchArgs.method = 'POST';
var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
"<category scheme='http://schemas.google.com/g/2005#kind' " +
"term='http://schemas.google.com/acl/2007#accessRule'/>" +
"<gAcl:role value='owner'/>" +
"<gAcl:scope type='user' value='"+userEmail+"'/>" +
"</entry>";
fetchArgs.payload = rawXML;
fetchArgs.contentType = 'application/atom+xml';
// Get the requested content (the ACL for the calendar)
var base = 'https://www.googleapis.com/calendar/v3/calendars/';
var url = base + calId + '/acl?key=' + API_KEY;
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(content);
}
//--------------------------------------------------------------
// Google OAuth
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API
Srik is right. You need to use oAuth Arguments in your UrlFetchApp.
Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs
https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth

IE crossdomain filter on flex application

I have an application that uses a flex form to capture user input. When the user has entered the form data (which includes a drawing area) the application creates a jpg image of the form and sends back to the server. Since the data is sensitive, it has to use https. Also, the client requires both jpg and pdf versions of the form to be stored on the server.
The application sends data back in three steps
1 - send the jpg snapshot with ordernumber
2 - send the form data fields as post data so it is not visible in the address bar
3 - send the pdf data
I am sending the jpg data first using urlloader and waiting for the server to respond before performing opperation 2 and 3 to ensure that the server has created the record associated with the new orderNumber.
This code works fine in IE over http. But If I try to use the application over https, IE blocks the page response from store jpg step and the complete event of the urlloader never fires. The application works fine in FireFox over http or https.
Here is the crossdomain.xml (I have replaced the domain with ""):
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*.<mydomain>.com" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*.<mydomain>.com" headers="*">
</cross-domain-policy>
Here is the code that is executed when the user presses the submit button:
private function loaderCompleteHandler(event:Event):void {
sendPDF();
sendPatientData();
}
private function submitOrder(pEvt:MouseEvent):void
{
//disable submit form so the order can't be submitted twice
formIsValid = false;
waitVisible = true;
//submit the jpg image first with the order number, userID, provID
//and order type. The receiveing asp will create the new order record
//and save the jpg file. jpg MUST be sent first.
orderNum = userID + "." + provID + "." + Date().toString() + "." + orderType;
var jpgURL:String = "https://orders.mydomain.com/orderSubmit.asp?sub=jpg&userID=" + userID + "&provID=" + provID + "&oNum=" + orderNum + "&oType=" + orderType;
var jpgSource:BitmapData = new BitmapData (vbxPrint.width, vbxPrint.height);
jpgSource.draw(vbxPrint);
var jpgEncoder:JPEGEncoder = new JPEGEncoder(100);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
var header:URLRequestHeader = new URLRequestHeader ("content-type", "application/octet-stream");
//Make sure to use the correct path to jpg_encoder_download.php
var jpgURLRequest:URLRequest = new URLRequest (jpgURL);
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = jpgStream;
//navigateToURL(jpgURLRequest, "_blank");
var jpgURLLoader:URLLoader = new URLLoader();
try
{
jpgURLLoader.load(jpgURLRequest);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred.");
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
jpgURLLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
}
private function sendPatientData ():void
{
var dataURL:String = "https://orders.mydomain.com/orderSubmit.asp?sub=data&oNum=" + orderNum + "&oType=" + orderType;
//Make sure to use the correct path to jpg_encoder_download.php
var dataURLRequest:URLRequest = new URLRequest (dataURL);
dataURLRequest.method = URLRequestMethod.POST;
var dataUrlVariables:URLVariables = new URLVariables();
dataUrlVariables.userID = userID
dataUrlVariables.provID = provID
dataUrlVariables.name = txtPatientName.text
dataUrlVariables.dob = txtDOB.text
dataUrlVariables.contact = txtPatientContact.text
dataUrlVariables.sex=txtSex.text
dataUrlVariables.ind=txtIndications.text
dataURLRequest.data = dataUrlVariables
navigateToURL(dataURLRequest, "_self");
}
private function sendPDF():void
{
var url:String = "https://orders.mydomain.com/pdfOrderForm.asp"
var fileName:String = "orderPDF.pdf&sub=pdf&oNum=" + orderNum + "&oType=" + orderType + "&f=2&t=1" + "&mid=" + ModuleID.toString()
var jpgSource:BitmapData = new BitmapData (vbxPrint.width, vbxPrint.height);
jpgSource.draw(vbxPrint);
var jpgEncoder:JPEGEncoder = new JPEGEncoder(100);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
myPDF = new PDF( Orientation.LANDSCAPE,Unit.INCHES,Size.LETTER);
myPDF.addPage();
myPDF.addImageStream(jpgStream,0,0, 0, 0, 1,ResizeMode.FIT_TO_PAGE );
myPDF.save(Method.REMOTE,url,Download.ATTACHMENT,fileName);
}
The target asp page is not sending back any data, except the basic site page template.
Can anyone help me figure out how to get around this IE crossdomain issue? I have turned off the XSS filter in IE tools security settings, but that still didn't solve the problem.
THANKS
Do everything over https. Load the swf from an https url. Send the initial form post via https. Send the images via https.