Postman localhost Authentication - api

I created an API with Laravel 4 that I want to test so I'm using postman. When I input my username, my password and my URL:
http://127.0.0.1/stores/public/locator/api/service/v1/store
A popup shows and tells me to enter my username and password for localhost:80. How do I solve this problem?
Here is the route :
Route::resource('store', 'StoreController');
Route::filter('Apiauth', function()
{
return Auth::basic("username");
);
Route::group(array('prefix' => 'locator/api/service/v1', 'before'=> 'Apiauth'), function()
{
Route::resource('store', 'StoreController');
});

You can include basic authentication in
http://username:passwordd#www.server.com/route
HTTP Basic Authentication credentials passed in URL and encryption

Related

Cypress: Login Authentication redirects to another domain: Workaround?

I understand that Cypress does not allow flipping from one domain to another domain because it will error with:
chrome-error://chromewebdata/
However, I need a workaround. I am providing a test set for multiple environments: STAGE, DEMO, PROD.
With DEMO and PROD, during the authentication phase (username/password), stay within the same domain:
VISIT: https://[demo|www].foo.com
AUTH: https://account.foo.com/auth >> username >> password
CONSENT: https://[demo|www].foo.com/action...
With STAGE, the authentication phase flips to another domain:
VISIT: https://[stage].foo.com
AUTH: https://account.bar.com/auth >> username >> password
CONSENT: https://[stage].foo.com/action...
Thereby, Cypress fails to redirect from VISIT to AUTH because of domain flip. This is blocking testing of STAGE.
What recommended workaround approaches?
Puppeteer?
Native Cypress using cy.request()?
Referenced:
Handling Cypress url redirect
Error with authentication in e2e tests using cypress: chrome-error://chromewebdata
Thank you, much appreciate the assistance.
The approach I took is similar to the Cypress Recipe Login with CSRF token
As mentioned, each deployment has its own website URL followed by account login URL.
Needed first is the CSRF token from account login page, which its URL is referred here as $baseUrl:
Cypress.Commands.add('cmdGetCSRF', ($baseUrl) => {
cy.log('COMMAND cmdGetCSRF');
expect($baseUrl)
.to.be.a('string')
.not.empty
cy.request($baseUrl)
.its('body')
.then(($body) => {
const $html = Cypress.$($body)
cy.log('html', $html)
const csrf = $html.find('input[name="__RequestVerificationToken"]').val()
expect(csrf)
.to.be.a('string')
.not.empty
return cy.wrap(csrf)
})
})
Then within body of requestOptions provided to cy.request() which will performing the login, provide one-time CSRF token:
const body: { [key: string]: string } = {
email: $envCypress.account_username,
password: $envCypress.account_password,
__RequestVerificationToken: $csrfToken
};
Cypress has recently add a new experimental feature for running test on multiple origins here. There are examples for cross origin login too. More on experimentalSessionAndOrigin feature:
https://docs.cypress.io/api/commands/origin
https://docs.cypress.io/api/commands/session

How to send Oauth token from callback at the server to the client?

I am using expressJs and passport for authentication. I am using Google Oauth2.0 for login with standard Passport GoogleStrategy. At client I am using axios for sending a login request to the server. My login routes are :
router.get(
"/google",
passport.authenticate("google", { scope: ["profile", "email"] }));
router.get(
"/google/callback",
passport.authenticate("google", { failureRedirect: "/"}),
function(req, res) {
const token = jwt.sign({id: req.user.id}, configAuth.secretKey);
console.log("generated token: ", token);
res.json({success: true, token: 'bearer ' + token});
}
);
I am using the user information from the callback to generate the JWT which I want to sent the client.
At the client I am using axios to send request and get the JWT and store it in localstore.
axios.get('http://localhost:3001/google')
.then((result) => {
console.log("result", result);
localStorage.setItem('jwtToken', result.data.token);
})
.catch((error) => {
// if(error.response.status === 401) {
// this.setState({ message: 'Login failed. Username or password not match' });
// }
console.log("Login error", error);
});
But Axios doesn't wait for the redirect to happen and returns a HTML document with Loading... message. If you try to access the API in the browser, it returns the desired JSON object. Is there a way to wait for redirects. Should I use another library to send login request?
I tried sending the token as url parameter with
res.redirect()
but client and server are at different ports so it doesn't work.
Is there another way to do it?
Google's OAuth2 pathway redirects your browser, resulting in page reloads, a couple of times before it completes. As a result, your client-side code,
axios.get('http://localhost:3001/google')
.then((result) => {
console.log("result", result);
localStorage.setItem('jwtToken', result.data.token);
})...
will never reach the .then() block. You probably see this in the browser; you click a button or something to navigate to 'http://localhost:3001/google', and your localhost:3001 server re-directs your browser to a Google login page. Now that your browser is at the login page, it has no memory of the axios.get statement above--that webpage code is gone.
You need to handle the JWT in client-side code that your server sends in response to
axios.get('http://localhost:3001/google/callback').
This is your browser's final stop in the OAuth2 path--once you get there, you won't be re-directed again. You can put your axios.get function above inside that client-side code.
If you haven't solved the problem, there is a workaround use 'googleTokenStategy' instead of googleOAuth on passportjs. That way you can use react's GoogleLogin plugin to receive the access token from the front end and send it by axios.post to the backend link then set up the jwt. Reference here

Axios get request not working with auth option

My Axios request is working fine as long as I'm typing in username and password manually.
But I would like to set the auth option to:
auth: {
user: this.username,
password: this.password
}
The moment i define the auth option, i get:
401 (Unauthorized)
Response for preflight has invalid HTTP status code 401
Why is my request not working with auth?
Can I get that running with auth?
Thanks in advance,
Simon

Not able to redirect to client side with token from server(express) side route

I am using 'googleapis' npm package to do token based google authentication.
I am redirected to '/api/auth/success/google' route inside express after google provided authentication and redirects us to the uri stated in google app credentials.
The problem I am facing is that ,I have retrieved the tokens on server side,but I am unable to send those tokens to client side for them to be saved in cookies.
The problem I am facing is because,'/api/auth/success/google' is redirected from google side and not an ajax call from client side.So if I send the tokens back in res,where will it redirect.Also please suggest a way to redirect from server side to client side,along with access_token.
server side code.
//Route reached after google successful login/authentication
app.get('/api/auth/success/google',function(req,res){
console.log("inside redirect");
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
oauth2Client.setCredentials(tokens);
}
res.sendFile('./index.html');
});
})
Client side call
//Google login requested from this function
googleLogin(){
event.preventDefault();
$.ajax({
type : 'POST',
url : baseURL + 'api/authenticate/google',
success: (function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}).bind(this)
});
}
//Route handling request of google access
app.post('/api/authenticate/google',function(req,res){
// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
googlecredentials.SCOPE[0],
googlecredentials.SCOPE[1]
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes // If you only need one scope you can pass it as string
});
res.send({ redirect: url });
})
//Google App Credentials
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(googlecredentials.CLIENT_ID, googlecredentials.CLIENT_SECRET, googlecredentials.REDIRECT_URL);
googlecredentials.CLIENT_ID - 858093863410-j9ma1i7lgapupip1ckegc61plrlledtq.apps.googleusercontent.com
REDIRECT_URL - http://localhost:3000/api/auth/success/google where localhost:3000 runs server side
If you send the redirect URL back in the res, the client-side should be able to check for the presence of the redirect URL in the response, and if it exists, push your user to that URL.

Ajax call with basic authentication works on desktop butnot on device browser

I have a weird issue.. I am trying to call a REST URL which is secured with basic authentication over https but for some reason the call doesn't go through when I perform it from a mobile device (iPhone/iPad). When I remove the basic authentication from the service the call goes through with authentication it just times out.
When I try to debug it on my desktop it works fine .. does anybody have any idea why this wouldn't work?
My call looks like this:
var values = this.getLoginForm().getValues();
Ext.Ajax.request({
url : '/some/relative/url/',
method : 'GET',
username: values.username,
password: values.password,
success: function(response){
loggedIn = true;
Ext.Msg.alert('Success', 'Logged In');
},
failure : function(response) {
Ext.Msg.alert('Error', response.responseText);
}
});
I tried with relative URL and with absolute and there seems to be no difference.
I am using Sencha Touch 2.3.1.