Get redirected URL from Postman - javascript

I'm currently migrating my old website to a new one and I have just created some url redirect rules to redirect old links to their pages on the new website.
In order to test these redirect rules I'm using Postman but I can't find any way of getting the redirected url from Postman's scripts documentation. REDIRECTED_URL is the url after being processed by the redirect rule.
Here is my current test:
var root_url = postman.getEnvironmentVariable('root_url');
var oldurl = root_url + postman.getEnvironmentVariable('old_page');
var newurl = root_url + postman.getEnvironmentVariable('new_page');
if (REDIRECTED_URL == newurl)
{
tests[oldurl + " redirected"] = true;
}
else
{
tests[oldurl + " failed to redirect"] = false;
}
Is there a way to test this in postman or should I be using another application?

Switch off the setting Automatically follow redirects in Postman.
Do a request to example.com/test-page/test01
In the test tab, check if the https status code and the re-direct header are correct:
pm.test("Status Code is 301", function () {
pm.response.to.have.status(301);
});
pm.test("Location-header exists", function () {
pm.expect(postman.getResponseHeader("Location")).to.eq("example.com/tests/test01");
});

Related

OAuth2 Implicit vs Authorization Code Grant for Fitbit API

THE ANSWER TO THIS QUESTION WAS IN THE FACT THAT I WAS USING AUTHORIZATION CODE GRANT FLOW ON THE CLIENT SIDE.. THIS SEEMS TO RESULT IN BLOCKING ERROR..
CHECK UNDERNEATH FOR FUNCTIONING AUTHENTICATION OAUTH2 IMPLICIT GRANT FOR FITBIT API..
I am performing OAuth2 authentication against the Fitbit API. This all using the Authorization Code Grant Flow. So first getting the auth code, being redirected to my application, then exchanging this for the access token and getting data with this token.
Starting off at the homePage on the "post_request.html" page, pushing the "fitbit" button, the user is redirected to the Authorization EndPoint of Fitbit. I am using Node.js to build a localserver to host the application and to be able to redirect without any problem..
On being redirected, I retrieve the authorization code and make an AJAX POST request to trade the authorization code for an access token. I then make this POST request but I get the following error..
{"errors":[{"errorType":"invalid_client","message":"Invalid authorization header format. The header was not recognized to be a valid header for any of known implementations or a client_id was not specified in case of a public client Received header = BasicdW5kZWZpbmVk. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."}],"success":false}
I think there might be an error in me url encoding the client_id and client_secret. Or in me setting the headers. But I cannot spot it. Can anyone help me out?
My HTML file is the following..
<body>
<button onclick="fitbitAuth()">Fitbit</button>
<!-- action = route, method = method -->
<form action="/" method="POST" id="form">
<h3>Email Address:</h3>
<input type="email">
<br>
<h3>Password:</h3>
<input type="password">
<br>
<br>
<button type="submit">Send Request</button>
</form>
</body>
</html>
My script is the following, it consists of 3 functions..
- base64 encoding function
- onclick function for starting the OAuth2 process
- function that trades in auth code for access token
// run this script upon landing back on the page with the authorization code
// specify and/ or calculate parameters
var url_terug = window.location.search;
var auth_code = url_terug.substr(6);
var granttype = "authorization_code";
var redirect_uri = "http://localhost:3000/fitbit";
var client_id = "xxxxx";
var client_secret = "xxxxxxxxxxxx";
var stringto_encode = client_id + ":" + client_secret;
var encoded_string = "";
console.log("auth code = " + auth_code);
function baseEncode(stringto_encode){
encoded_string = btoa(stringto_encode);
console.log(encoded_string);
}
function getTokenFitBit(){
baseEncode();
// execute a POST request with the right parameters
var request = new XMLHttpRequest();
request.open('POST', "https://api.fitbit.com/oauth2/token?client_id=" + client_id + "&grant_type=" + granttype + "&redirect_uri=" + redirect_uri + "&code=" + auth_code);
request.setRequestHeader('Authorization', 'Basic'+ encoded_string);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Setup our listener to process completed requests
request.onload = function () {
// Process our return data
// status code between 200 and 300 indicates success
if (request.status >= 200 && request.status < 300) {
console.log('success!', request);
console.log(request.responseText);
// continue with API calls..
// you could set up a broader response handling if there is a use case for it
} else {
console.log('The current token request failed!');
}
};
request.send();
}
getTokenFitBit();
// get the access token out of the JSON response
// execute a GET request on the API endpoint
// handle the data
// upon clicking fitbit button, starting off the oauth2 authentication
function fitbitAuth() {
window.location.href = 'https://www.fitbit.com/oauth2/authorize?client_id=xxxxx&response_type=code&scope=activity&redirect_uri=http://localhost:3000/fitbit&prompt=consent';
}
In the above example, you appear to have missing a separator between the "Basic" header and it's value in this line:
request.setRequestHeader('Authorization', 'Basic'+ encoded_string);
Provided you are building a web based applications, you may want to look into using the 'Implicit' Flow, too: https://oauth.net/2/grant-types/implicit/
The following code functions and uses the implicit grant flow. It works with FitBit API, Node.js to redirect to the application, and then client-side authentication.
Code for the Node.js local server module
// PROJECT authenticating Fitbit OAuth2 Implicit Grant
const express = require("express");
const app = express();
const filesys = require("fs");
const path = require("path");
// body parser module parses form data into server
const body_parse = require("body-parser");
// middleware to encrypt folder structure for users : can look into DevTools
app.use('/public', express.static(path.join(__dirname, 'static')));
// allows us to parse url encoded forms
app.use(body_parse.urlencoded({extended: false}));
// using readstream with chunks in buffer with security on the path
app.get("/fitbit", (req, res) => {
const readStream = filesys.createReadStream(path.join(__dirname,'static','post_request.html'));
readStream.on('error', function(){
/*handle error*/
res.write("there is an error authenticating against fitbit api endpoint");
});
res.writeHead(200, {'Content-type' : 'text/html'});
readStream.pipe(res);
});
// bodyparser parses data and adds to the body of the request
app.get("/", (req, res, err) => {
const readStream = filesys.createReadStream(path.join(__dirname,'static','start_page.html'));
res.writeHead(200, {'Content-type' : 'text/html'});
readStream.pipe(res);
});
app.listen(3000);
HTML file for the start page, with just a button to initiate the OAuth2 process..
<body>
<button onclick="fitbitAuth()">Fitbit</button>
<script>
// define variables
var cli_id = "xxxxx";
var res_typ = "token";
var scope_typ = "activity";
var redirect = "http://localhost:3000/fitbit";
var expires = "31536000";
var prompt_var = "consent";
// upon clicking fitbit button, starting off the oauth2 authentication
function fitbitAuth() {
window.location.href = "https://www.fitbit.com/oauth2/authorize?client_id=" + cli_id + "&response_type=" + res_typ + "&scope=" + scope_typ + "&redirect_uri=" + redirect + "&expires_in=" + expires + "&prompt=" + prompt_var;
}
</script>
</body>
</html>
The redirect page, the page the user gets sent back to after consenting using his/ her data.. With just one button to initiate API call on lifetime activity stats..
<body>
<!-- action = route, method = method -->
<button type="submit" onclick="getActivityData()">Send Request</button>
<script>
// get out the accesstoken from the provided data
var url_terug = window.location.href;
var split_after = "access_token=";
var split_before = "&user_id";
var after_string = url_terug.split(split_after).pop();
var accesstoken = after_string.slice(0, after_string.indexOf(split_before));
console.log(accesstoken);
// getActivityData();
function getActivityData(){
// execute a POST request with the right parameters
var request = new XMLHttpRequest();
request.open('GET', "https://api.fitbit.com/1/user/-/activities.json");
request.setRequestHeader('Authorization', 'Bearer '+ accesstoken);
// Setup our listener to process completed requests
request.onload = function () {
// Process our return data
// status code between 200 and 300 indicates success
if (request.status >= 200 && request.status < 300) {
console.log('success!', request);
console.log(request.responseText);
// continue with API calls..
// you could set up a broader response handling if there is a use case for it
} else {
console.log('The current token request failed!');
}
};
request.send();
}
</script>
</body>

window.location issue on hubspot

window.location will redirect to external links like google, but won't redirect to a url with the same domain from where it originates (it'll link to sub-domains, though). This came from a hubspot form, customized to redirect the user to a specific thank-you page based on their inquiry type. This is all in wordpress. There is no issue defining the choice variable. I'm new to JavaScript, thanks for any help.
onFormSubmit: function($form) {
var choice = $('select[name="form_field_dropdown_select"]').val();
if (choice == 'Support') {
window.location = 'https://www.mycompany.com/support-thank-you/';
} else {
window.location = 'https://www.washingtonpost.com/';
}
}
I'm running this code through my console because I know the choice variable is set up correctly. The error I'm getting is an Uncaught SyntaxError: Unexpected token ( on the line onFormSubmit: function($form)
onFormSubmit: function($form) {
var choice = "Support";
if (choice == 'Support') {
window.location = 'https://newcloudnetworks.com/support-thank-you';
} else {
window.location = 'https://www.washingtonpost.com/';
}
}
Additionally, I can see the redirect initially going to the support page but then immediately redirecting to the default/home page.
[21/Mar/2019:11:13:44 -0600] "GET /support-thank-you HTTP/1.1" 200 6015
[21/Mar/2019:11:13:46 -0600] "GET / HTTP/1.1" 200 9683
The issue has been resolved. It was an issue I had to raise hell with to Hubspot and they were able to resolve. It had nothing to do with an error in the JS code. Thanks.
So, you need to provide more info, but I'll assume your:
hostname(domain): www.mycompany.com
So you can add another check for the domain the form was used.
const myDomain = 'www.mycompany.com';
onFormSubmit: function($form) {
var choice = $('select[name="form_field_dropdown_select"]').val();
if (choice == 'Support') {
let domain = window.location.hostname;
if (myDomain == domain) {
// change path if the form is used in your domain
window.location.pathname = 'support-thank-you';
} else {
// redirect to you domain
window.location = 'https://www.mycompany.com/support-thank-you/';
}
} else {
window.location = 'https://www.washingtonpost.com/';
}
}

Without login access to drive files by api in javascript (web application)

I'm using javascript with drive + spreadsheet api. Now I am able to get the access token. But I tries a lot with stack answers and google guide for get refresh token request. But I did not found any way that how to access the refresh token by access token. Please help me with some code.
My script is:
var _url = https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&client_id={my_client_id}&client_secret={My_secret_key}","redirect_uri=httpmypath to currentrunningfile/oauth&response_type=token
function getAccessDetails() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
console.log('url is :'+url);
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
console.log('acToken :' + acToken + 'tokenType :' + tokenType + 'expiresIn :' + expiresIn);
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
What is the next step and how to code it for access the refresh token? Actully I want user to login first time to app with their google login details for their drive files access by my app. The next time when user use my app to access his drive files. He can access files without login.

How to Use 1 file for different Action?

I have 2 files, there are Index.aspx and AdminHome.aspx. and also have javascript file (test.js) for logic behind.
Index and adminHome is actually same but the different is only the redirect action.
If I run program from Index.aspx then i'll be redirect to CheckSeat.aspx
If I run program from AdminHome.aspx then I'll be redirect to AdminCheckSeat.aspx. I want to use same Javascript because each file has same logic. only the redirect file is the different.
this is my redirect code on .js
var url = "CheckSeat.aspx?noSeat=" + encodeURIComponent(lObjSeat[0].Name) + "&endtime=" + encodeURIComponent(time);
window.location.replace(url);
so Is it possible to do ?
if ya, How do you do ?
example URL : http://localhost90909/abcd/index.aspx
I need 'index.aspx' segment only
You may replace the url based on current page.
if (document.URL = 'Index.aspx') {
var url = "CheckSeat.aspx?noSeat=" + encodeURIComponent(lObjSeat[0].Name) + "&endtime=" + encodeURIComponent(time);
window.location.replace(url);
}
else if (document.URL = 'AdminHome.aspx') {
var url = "AdminCheckSeat.aspx"
window.location.replace(url);
}

is it possible to redirect the user to same page after login using client side technology

I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.

Categories

Resources