JWT with AngularJS not storing token - laravel

My token is currently being retrieved on the Laravel end. I used Postman to verify this.
I want to decrypt and store my token into local storage for a session with the user, but not sure how to go about this. I want to just put it in the login function which is currently doing the following:
$scope.login = function() {
$http.post('http://thesis-app.dev/login', $scope.user, {headers: {'X-
Requested-With': 'XMLHttpRequest'}}).success(function(response) {
console.log($scope.user);
})
.success(function(){
console.log("user logged in!");
console.log(response)
})
.error(function() {
console.log("their was an error");
console.log(response);
});
}

Related

Axios interceptor doesn't intercept on page load

I am implementing JWT into my Vue application for authorization and I refresh my tokens once they are used.
I have used axios interceptors so I can intercept every request to my API backend and this seems to work on login etc... but once I refresh the page the request is made as normal using the last token.
The problem is the axios interceptors don't seem to work at this point, so once the token has been used I can't update it with the new one.
Here's how I'm setting my interceptors:-
window.axios.interceptors.request.use(function (config) {
console.log("Sent request!");
return config;
}, function (error) {
console.log("Failed sending request!");
return Promise.reject(error);
});
window.axios.interceptors.response.use(function (response) {
console.log("Got headers:", response.headers);
if (response.headers.hasOwnProperty('authorization')) {
console.log("Got authorization:", response.headers.authorization);
Store.auth.setToken(response.headers.authorization);
}
return response;
}, function(err){
console.log("Got error", err);
});
I don't get any of the console.log's on page load.
I am setting my interceptors in the root app's beforeMount method. I've tried moving them to beforeCreate and I still get the same issue.
try this
window.axios.interceptors.request.use(function (config) {
console.log("Sent request!");
if(localStorage.getItem('id_token')!=undefined){
config.headers['Authorization'] = 'Bearer '+localStorage.getItem('id_token')
}
return config;} , function (error) {
console.log("Failed sending request!");
return Promise.reject(error); });

Stormpath secure rest api

I followed the example here https://stormpath.com/blog/the-ultimate-guide-to-mobile-api-security
and here to acquire an access token
https://support.stormpath.com/hc/en-us/articles/225610107-How-to-Use-Stormpath-for-Token-Management
"use strict";
import { ApiKey } from 'stormpath';
import { Client } from 'stormpath';
let apiKey = new ApiKey(process.env.STORMPATH_API_KEY_ID,
process.env.STORMPATH_API_KEY_SECRET);
let spClient = new Client({apiKey: apiKey });
spClient.getApplication(process.env.STORMPATH_APPLICATION_HREF,
function(err, app) {
var authenticator = new OAuthAuthenticator(app);
authenticator.authenticate({
body: {
grant_type: 'password',
username: username,
password : password
}
}, function (err, result) {
if (!err) console.log(err);
res.json(result.accessTokenResponse);
});
});
I was able to acquire a access_token. I use this token to hit my api with Header Authorization Bearer {access_token}
However, when i put in the middleware stormpath.apiAuthenticationRequired, i keep getting this warning and my api is returned with 401
(node:57157) DeprecationWarning: JwtAuthenticator is deprecated, please use StormpathAccessTokenAuthenticator instead.

Parse On Buddy Logout User

I am migrating an application from parse.com to buddy.com. One of the caveats of the migration was that Parse.User.current() is no longer available on buddy.com, instead you have to get the user and session token from the request itself: https://github.com/ParsePlatform/Parse-Server/wiki/Compatibility-with-Hosted-Parse#no-current-user
The application I am migrating has a logoutUser method that I am attempting to migrate:
Parse.Cloud.define("logoutUser", function(request, response) {
Parse.User.logOut().then(
function onSuccess(result){
response.success(result);
},
function onError(error) {
response.error(error);
}
)
});
now I am attempting to do this in the new style, but am receiving an error. (NOTE: This is cloud code not a nodejs environment)
{
"code":"500",
"error":"Error: There is no current user user on a node.js server environment."
}
New implementation:
function logoutUser(request, response) {
var user = request.user;
var sessionToken = user.getSessionToken();
Parse.User.logOut({ sessionToken }).then(
function onSuccess(result){
response.success(result);
},
function onError(error) {
response.error(error);
}
)
}
Parse.Cloud.define("logoutUser", function(request, response) {
logoutUser(request, response);
});
Suggestions on how to correctly log out users in the Parse on Buddy cloud code?
You could fetch user's session or sessions and delete it / them:
var query = new Parse.Query("_Session");
query.descending('createdAt');
query.equalTo('user', {__type:"Pointer", className:"_User", objectId:"idhere"});
query.first({
useMasterKey: true
}).then(function(session) {
var sessions = [];
sessions.push(session);
Parse.Object.destroyAll(sessions);
}, function (err) {
console.log("Internal error " + err);
});
OR for more tokens you could use find instead of first like:
var query = new Parse.Query("_Session");
query.equalTo('user', {__type:"Pointer", className:"_User", objectId:"idhere"});
query.find({
useMasterKey: true
}).then(function(sessions) {
Parse.Object.destroyAll(sessions);
}, function (err) {
console.log("Internal error " + err);
});
The above will mostly delete or tokens related to the given user. If you wish to delete only tokens used for login, and not for signup or upgrade, then you could put into your query:
query.equalTo('createdWith', { action: 'login', authProvider: 'password'});
As far as i know, deleting a user's last used for login token, then he is logged-out.
To add to the above, if you pass up the user's session key to the Cloud Code function via the X-Parse-Session-Token header, you can use the populated request.user object in the session query directly, instead of the user's ID.

Parse express server side login using express-session

I'm using parse on node. I have an express app, and a JS browser app, that is hosted off the express server.
At the moment the app has it's own login. It logs the user in on the client, and the client remains logged in.
I want to be able to log the client in via an express route /login. When they log in via this route, i want to log them in on the client side.
I have poured over documentation on this but I have struggled to find any real examples of how this is all done.
Here is some code i have found:
var cookieSession = require('cookie-session'),
// I added this require as it seems the code is using it;
session = require('express-session');
app.use(cookieSession({
name: COOKIE_NAME,
secret: "SECRET_SIGNING_KEY",
maxAge: 15724800000
}));
//
// This will add req.user if they are logged in;
//
app.use(function (req, res, next) {
Parse.Cloud.httpRequest({
url: 'http://localhost:1337/parse/users/me',
headers: {
'X-Parse-Application-Id': 'myAppId',
'X-Parse-REST-API-Key': 'myRestAPIKey',
'X-Parse-Session-Token': req.session.token
}
}).then(function (userData) {
req.user = Parse.Object.fromJSON(userData.data);
next();
}).then(null, function () {
return res.redirect('/login');
});
});
//
// login route;
//
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
req.session.user = user;
req.session.token = user.getSessionToken();
res.redirect('/');
}, function(error) {
req.session = null;
res.render('login', { flash: error.message });
});
});
//
// and logout.
//
app.post('/logout', function(req, res) {
req.session = null;
res.redirect('/');
});
This looks pretty good, but this won't add a session on the client? How do parse the server login down to the client; Do i pass the session Token and use it on the client?
//
// If i call this code in the browser, i want the logged in user;
//
var current_user = Parse.User.current();
I have been unable to find any real code on-line that demonstrates all of this in the best-practice manner.
Is this the 'best practice' known solution or is there a better way of doing this?

SailsJs :: Keep sessions with mocha

I need to keep my sessions alive between to mocha requests.
After login, I store in the user id in the express session object :
req.session.user = user.id ;
On a browser, the session is kept without any question needed (tested with Postman).
But, I need to make my REST API reachable for an external app, and I would like not to have to authenticate for each request on my API.
Is there a way for me to be able to keep the session between two requests in mocha or via the client app of the API ?
Thanks by advance.
English is not my mother langage, I may have not been as clear as I would have wanted. So I can provide any information you might need to help me.
UPDATE
Thanks to Alberto, I figured out how to keep my sessions alive in Mocha with Supertest.
An agent keeps his sessions until its it destroyed, or the logout is requested.
What needs to be donne is use the same agent to login and for requesting the API.
What I did is :
var request = require('supertest'),
should = require('chai').should();
describe('ImageController', function() {
var agent = request.agent('http://localhost:1337') ;
before(function(done){
agent
.post('/auth/local')
.send({identifier: 'email', password: 'password'})
.end(function(err, res) {
if (err) return done(err);
done();
});
})
after(function(done){
agent
.get('/logout')
.end(function(err, res) {
if (err) return done(err);
done();
});
})
describe('POST /image', function(){
it('should return 201 for image creation after login', function (done) {
agent
.post('/image')
.send({name: 'test.png'})
.end(function (err, res) {
if (err) return done(err);
res.status.should.be.equal(201);
done();
});
});
});
});
Use supertest agent feature how can store cookies.
Has one example in supertest docs: https://github.com/tj/supertest#example
Sails.js example with super test example: https://github.com/albertosouza/sails-test-example
Test file example snipplet:
var request = require('supertest');
var assert = require('assert');
var authenticated;
describe('Example test', function() {
// use efore all to create custom stub data
before(function(done) {
// use supertest.agent for store cookies ...
// logged in agent
// after authenticated requests
//login and save one agent with your session cookies. Ex:
authenticated = request.agent(sails.hooks.http.app);
authenticated.post('/auth/login')
.send({
email: user.email,
password: user.password
})
.end(function(err) {
done(err);
});
});
describe('authenticated requests', function(){
it ('should access one protected route', function(done){
// use the authenticated agent to do authenticated requests
authenticated.get('/protected')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log('response:', res.text);
done();
});
});
});
});

Resources