How to edit body before send request with Fiddler(script) - fiddler

How to edit body before send request with Fiddler(script)
in my case path /login
have body
username: xxx
pass: xxxx
how to edit user pass before send send request

static function OnBeforeRequest(oSession: Session) {
var loginDomain = 'www.testlogin.org';
var loginPath = '/login';
var username;
var password;
var strBody
if (username == null && oSession.uriContains(loginDomain) &&
oSession.uriContains(loginPath))
{
username = FiddlerObject.prompt("Enter user name: ");
password = FiddlerObject.prompt("Enter password: ");
strBody='username: ' + username + ' pass: ' + password;
//encode the body to handle special characters in the password
//password "P&ssword=secure" will be "P%26ssword%3Dsecure"
strBody=Utilities.UrlEncode(strBody);
oSession.utilSetRequestBody(strBody);
}
//... the rest of the OnBeforeRequest function
}
This will open 2 prompt windows to enter the username and then password
after entering the login URL in a browser and executing a request. The prompts may not popup in front of the browser, you may need to switch focus to fiddler to use the prompt windows

For modifying requests in Fiddler classic use the OnBeforeResponse function. To replace username and password in body of the HTTP request (not in header as used e.g. by BASIC auth) you can use utilReplaceInRequest method which performs search and replace on text level:
static function OnBeforeResponse(oSession: Session) {
// check if the requests is to the correct hosts and path
if (oSession.HostnameIs("www.example.org") && oSession.PathAndQuery.Contains("/login")) {
oSession.utilDecodeResponse();
oSession.utilReplaceInRequest("username: xxx", "username: newusername");
oSession.utilReplaceInRequest("pass: xxxx", "pass: newpassword");
}
}
Alternatively you can get the body as text and manipulate it as you want using standard .Net String methods:
if (oSession.HostnameIs("www.example.org") && oSession.PathAndQuery.Contains("/login")) {
oSession.utilDecodeResponse();
var body = oSession.GetRequestBodyAsString();
// use .Net String manipulation methods to find and replace text in the body
oSession.utilSetRequestBody(body);
}

Related

How can I get "Amazon.Extensions.CognitoAuthentication.CognitoUserSession.IDToken" From AWSCredentials?

I want get "Amazon.Extensions.CognitoAuthentication.CognitoUserSession.IDToken" From AWSCredentials.
I have AWSCredentials From Oauth Google Login.
public AWSCredentials GetAWSCredentials_Google(string token)
{
CognitoAWSCredentials credentials = new CognitoAWSCredentials(FED_POOL_ID, regionTable[REGION]);
credentials.AddLogin("accounts.google.com", token);
return credentials;
}
And, I use EC2 Instance and my ubuntu server is in there. Also, I was originally using a method of accessing the server by receiving a membership from Cognito User Pool, so I was using the following code.
private IEnumerator sendPostUser()
{
string uri = rootUrl + "/user";
string json = "{ ... }";
byte[] jsonData = System.Text.Encoding.UTF8.GetBytes(json);
using (UnityWebRequest request = UnityWebRequest.Post(uri, json))
{
if (request.uploadHandler != null)
request.uploadHandler.Dispose();
request.disposeUploadHandlerOnDispose = true;
request.disposeDownloadHandlerOnDispose = true;
request.uploadHandler = new UploadHandlerRaw(jsonData);
/* Header */
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("token", cloud_acess.GetComponent<ControlCloud>().cognitoUser.SessionTokens.IdToken);
/* Send Message */
yield return request.SendWebRequest();
...
}
By the way, there was a problem with this code "request.SetRequestHeader("token", cloud_acess.GetComponent().cognitoUser.SessionTokens.IdToken);".
This cognitouser means Amazon.Extensions.CognitoAuthentication.CognitoUser.
My Project get CognitoUser using user's ID and PW, and get AWSCredentials using this Cognitouser. But Google Login doesn't this process and just get credentials.
So, I can't get "cognitoUser.SessionTokens.IdToken". It makes me cannot to request anything from ec2 server.
How Can i get this? What should I do if the premise of this problem itself is wrong?
I tried to put all the tokens I received when I logged in to Google and the tokens I received as credentials in the header.But I failed.

Keycloak: how to get client_id where the user registered?

I have a realm with several OpenId clients using SSO. I need to determine from which client each Keycloak user came from.
How can I get this information?
Answering my own question.
I didn't find natively this information in Keycloak's token. So I added a script.
In Authentication > Registration flow, I add an execution of type "Script" with the following function:
function authenticate(context) {
var username = user ? user.username : "anonymous";
var uri = context.getUriInfo();
LOG.info("setClientIdAttribute for URI " + context.getUriInfo().getRequestUri());
if (uri !== null) {
var clientId = uri.getQueryParameters().getFirst("client_id");
if (clientId !== null) {
LOG.info("Attribute 'origin' set with value " + clientId + " for user " + username);
user.setSingleAttribute('origin', clientId);
}
}
context.success();
}
If decoded each JWT has parameter azp, which is the client id.
If you decode the token, the field "aud" is your "client_id".
Check this information using jwt.io.

Why is my cookie always null?

I don't get this. An hour ago it worked and all of a sudden I can't get back the cookie I just set. Under Chrome I can see that the cookie is actually there but if I try to get it back it's null:
private void setLoggedInCookie(String sessionId) {
String domain = this.getDomain();
Cookies.setCookie(ApiParameters.LOGIN_COOKIE, sessionId, expires, domain, "/", true);
String cookie = Cookies.getCookie(ApiParameters.LOGIN_COOKIE);
// Getting NOTHING from this ..
for (String string : Cookies.getCookieNames()) {
LOGGER.info("Cookie name: " + string);
}
if(cookie == null) {
throw new RuntimeException("Cookie is 'null'.");
}
}
private String getDomain() {
LOGGER.fine("Host name: " + Window.Location.getHostName());
String domain = Window.Location.getHostName().replaceAll(".*//", "").replaceAll("/", "").replaceAll(":.*", "");
return "localhost".equalsIgnoreCase(domain) ? "localhost" : domain;
}
What is happening?
You pass domain name "null". Browsers allow access only to cookies associated with the current page's domain. Since you are trying to access it from a page which is not "null", you can't get it.
Also, make sure you are trying to access it using SSL, since you set "secure" parameter to true.

Changing user folder collaborating type in box using Salesforce Toolbox

I'm trying to change Box folder collaboration type for user from salesforce Apex trigger. The first thoughts were to use box.Toolkit but it looks like this class does not have updateCollaboration or changeCollaboration method, only create. I guess my only option is to use Box's Rest API. Is there any way I can get service account token in Apex so I can use it in a callout?
I have created a special "Tokens" object in Salesforce with two fields: access token and refresh token. I then have a batch job that runs to update the access token every 55 minutes such that they never expired.
Here is a code snippet in APEX using the Tokens object.
#future(callout=true)
public static void updateTokens(){
//app info for authenticating
String clientID = 'MY_CLIENT_ID';
String clientSecret = 'MY_CLIENT_SECRET';
//look up value of existing refresh token
Token__c myToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Refresh'];
Token__c myAccessToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Access'];
String refreshToken = myToken.Value__c;
String accessToken = myAccessToken.Value__c;
//variables for storing data
String BoxJSON = '';
String debugTxt = '';
//callout to Box API to get new tokens
HttpRequest reqRefresh = new HttpRequest();
reqRefresh.setMethod('POST');
String endpointRefresh = 'https://www.box.com/api/oauth2/token';
reqRefresh.setEndpoint(endpointRefresh);
String requestBody = ('grant_type=refresh_token&refresh_token=' + refreshToken + '&client_id=' + clientID + '&client_secret=' + clientSecret);
reqRefresh.setBody(requestBody);
System.debug('Body of refresh request: ' + requestBody);
//Create Http, send request
Http httpRefresh = new Http();
Boolean successRefresh = false;
while (successRefresh == false){
try{
HTTPResponse resRefresh = httpRefresh.send(reqRefresh);
BoxJSON = resRefresh.getBody();
System.debug('Body of refresh response: ' + BoxJSON);
successRefresh = true;
}
catch (System.Exception e){
System.debug('Error refreshing: ' + string.valueof(e));
if (Test.isRunningTest()){
successRefresh = true;
}
}
}
Keep in mind that if you are using the Box for Salesforce integration your administrator can set the option for the permissions on the folders to sync with Salesforce permissions. This would reverse any changes you make to collaborations. Check out more about Box's Salesforce integration permissions here: https://support.box.com/hc/en-us/articles/202509066-Box-for-Salesforce-Administration#BfS_admin_perm

Azure Mobile Service Single Sign on Microsoft Account

I have implemented single sign on using the WL api, but I only recently realized that I need to call mobileService.login on top of that to use the nice authentication features of Azure Mobile Services.
I followed this tutorial
http://www.windowsazure.com/en-us/develop/mobile/tutorials/single-sign-on-windows-8-js/#add-authentication
and added this piece of code:
var login = function () {
return new WinJS.Promise(function (complete) {
WL.init();
WL.login({ scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"] }).then(function (result) {
session = result.session;
WinJS.Promise.join([
WL.api({ path: "me", method: "GET" }),
mobileService.login("microsoftaccount", session.authentication_token)
]).done(function (results) {
var profile = results[0];
var mobileServicesUser = results[1];
var title = "Welcome " + profile.first_name + "!";
var message = "You are now logged in as: " + mobileServicesUser.userId;
var dialog = new Windows.UI.Popups.MessageDialog(message, title);
dialog.showAsync().done(complete);
});
}, function (error) {
session = null;
var dialog = new Windows.UI.Popups.MessageDialog("You must log in.", "Login Required");
dialog.showAsync().done(complete);
});
});
}
however on this line
mobileService.login("microsoftaccount", session.authentication_token)
my session.authentication_token is undefined. (I have an access_token)
If I don't pass the token, I am prompted to sign in every time I launch the app, which defeats the purpose of the integrated sign on.
Any ideas?
To get the authentication token, you need to pass the redirect URI to the call to WL.init:
WL.init({
redirect_uri: "<< INSERT REDIRECT DOMAIN HERE >>"
});
Where the redirect domain must be the same as the one in your Live Connect application.