I'm want to test the oauth2 (nodejs) in postman.
So, I made this route:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
});
Postman, I set this Url (which point to my route):
It's work. It gets to this route. but I am not able to find how to close this window and get the token?
What should the response look like?
I searched everywhere on the web and could not find any information about it.
I have try this but still not working:
router.get('/authorise', (req, res, next) => {
console.log('in authorise');
res.writeHead(302, {
Location: 'https://www.getpostman.com/oauth2/callback?access_token=8ba64c1fbe8d4c3a892e432425842adde38fbb0e&response_type=code'
});
res.end();
});
You need to open the window from the client side not from the Node application and when you receive the response from Node you can close the window.
I Found!
Just need to return AUTHORIZATION_CODE like so:
res.redirect(url.format({
pathname: "https://www.getpostman.com/oauth2/callback",
query: {
code: `AUTHORIZATION_CODE`
}
}));
Then is continue to Access Token Url.
Related
I have an express/react app which runs just fine, it is a single-page app. I needed to make some changes on the server side regarding authentication, but I noticed that running the express server my app was not serving the updated .get function. Any thoughts on why this might be happening?
Old function
app.get('/app/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'))
})
New function:
app.get('/app/', async (req, res) => {
const authorized = await checkSession(req)
if (!authorized) { res.redirect('/login'); return}
res.send("OK")
})
I suppose I should get a plain OK as a response in the browser, but even changing the server port, browser or anything I can think of I get the old page. Any help is much appreciated.
Remove the trailing slash on the first parameter of app.get():
app.get('/app', async (req, res) => {
const authorized = await checkSession(req)
if (!authorized) { res.redirect('/login'); return}
res.send("OK")
})
try to remove async/await because when you use this checkSession return one promise and continue to execute the rest os the code in this case you have to wait the return of checkSession before verify if is authorized.
I'm trying to get the user data back from my database, but I can't seem to figure out how to send a query param to my server in order to do such a thing. My angular front end is running on a different port than my server (not sure that matters) but I can't figure it out.
I've tried using http.get to call the backend, but that doesn't seem to work.
This is the code in my auth.service:
reload() {
this.http.get('/user', {params: {userId: 'test'}});
}
This is the code on my server
app.get("/user/?userId", (req, res, next) => {
console.log('hello 2ddsaczczxczxC')
console.log(req);
})
My console logs aren't logging anything so it's clearly not reaching the backend at all.
Here is the change required for accessing any as such request parameters. Update your rest end point to
/user/:userid
app.get("/user/:userId", (req, res, next) => {
console.log('hello 2ddsaczczxczxC')
console.log(req.params);
})
Then access the query using either by request.params or req.query please check the documentation of expressjs as well.
You can try this:
app.get("/user/:userId", (req, res, next) => {
console.log();
}
You can pass query parameter by doing this
reload() {
this.http.get('/user', {queryParams: {userId: 'test'}});
}
I want to redirect a get request to another server post. i don't know how to do that. the following is my code.
server 1: get method
app.get('/sampleTestApp', function (req, res) {
body={uid:'test'}
// Want to redirect here to server 2 'login/callback' url with body object
}
server 2: post method
app.post('/login/callback', function (req, res) {
// success process..
}
You can do something like
app.get('/sampleTestApp', function (req, res) {
axios.post(url:'server2/post', data :body={uid:'test'},function(response) {
res.send(response);
})
}
I'm creating a simple PWA to draw in multiple data sources into one application. I'm currently trying to set up authentication using a combination of passport and the twitter-strategy.
After the user has successfully authenticated they're account, twitter redirects to the callback endpoint, with the valid user data.... essentially the auth has been successful. However, when sending the user back to the client side application a html document with the word null is presented, rather than the application.
With the following code, I expect:
Twitter to return to callback URL
Server to perform actions in authSuccess function
Redirect to the provided url on the client
routes.js to server the application shell via the catch all route
Client application to boot and handle the URL served
Currently, only the first two steps are successful, and the app simply displays null (with the correct url in the address bar), rather than the expected output. Changing the location of the writeHead() call to / works, and the user is authenticated as expected ().
routes.js
let users = require('../controllers/userController');
app.get('/user/auth/twitter/callback',
passport.authenticate('twitter', {
failWithError: true
}),
function(req, res) {
console.log('[Twitter] Auth success route hit');
users.authSuccess(req, res);
},
function(err, req, res, next) {
console.log('[Twitter] Auth failure route hit');
users.authFailure(err, req, res, next);
}
);
app.get('*', function(req, res){
console.log('[Route] Catch All: ' + req.path);
res.sendFile(path.resolve(__dirname, '../../public/index.html'));
});
userController.js
authSuccess(req, res) {
console.log('[User Controller] User',req.user);
// Set some cookies here
res.writeHead(302, {'Location': '/user/profile'});
// res.redirect('/user/profile');
res.end();
}
Any help much appreciated. If you need more code, just ask :)
Thanks
I'm trying to set up a web server using express. To access this server, users have to authenticate and for that, I use the basicAuth() middleware provided by Express. It works perfectly, except that I do not know how to log out once I logged in ! I have to close my browser to disconnect, but instead I would like to have a "disconnect" page which would redirect towards the "login" page (this one with the hideous form used to log in...).
Does anyone has an idea ?
Thanks per advance
PS : I apologize for my pathetic English :)
Express' basicAuth uses HTTP Basic Authentication whose implementation doesn't need HTML pages, cookies nor session ids. Its main drawbacks are its not secure and, our concern here, there is no mechanism in the spec for the server to instruct the browser to log out.
express.basicAuth() calls require(blah-blah/connect/lib/utils).unauthorized() which sends a 401 status with header 'WWW-Authenticate: Basic realm="..."'. The browser handles the authentication window and from then on sends a header like 'Authorization: Basic YmFzaWM6YmFzaWM=' which contains the username and password.
(express.basicAuth is not secure, especially over HTTP, because you can get the username:password with
new Buffer('YmFzaWM6YmFzaWM=' , 'base64').toString()
which gives basic:basic in this case.)
Our problem is the HTTP spec does not provide a way to stop that header being sent. A workaround for HTTPS is to redirect the user to a URL on the same domain having incorrect credentials.
The HTTP workaround I use for Express V3 can be used with app.use(express.basicAuth(...)). I find this easier to use than other solutions which require a call to middleware in every secured route, e.g. app.get('/secure', checkAuth, function (req, res) {...}).
Here is a working example.
var express = require('express'),
http = require('http'),
app = express();
app.use(express.favicon()); // prevent interference during test
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'winter is coming' }));
app.use(function (req, res, next) {
if (!req.session.authStatus || 'loggedOut' === req.session.authStatus) {
req.session.authStatus = 'loggingIn';
// cause Express to issue 401 status so browser asks for authentication
req.user = false;
req.remoteUser = false;
if (req.headers && req.headers.authorization) { delete req.headers.authorization; }
}
next();
});
app.use(express.basicAuth(function(user, pass, callback) {
callback(null, user === 'basic' && pass === 'basic');
}, '***** Enter user= basic & password= basic'));
app.use(function (req, res, next) {
req.session.authStatus = 'loggedIn';
next();
});
app.use(app.router);
app.get('/secure', function (req, res) {
res.send([
'You are on a secured page.',
'<br>',
'Refresh this page without having to log in again.',
'<br/>',
'Log out.'
].join(''));
});
app.get('/logout', function (req, res) {
delete req.session.authStatus;
res.send([
'You are now logged out.',
'<br/>',
'Return to the secure page. You will have to log in again.',
].join(''));
});
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000. Point browser to route /secure');
});
P.S. Your English is excellent.
For express.js 4 and basicAuth, you can use this method:
app.get('/logout', function (req, res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
});
Adding to wyllman, the 401 code is Unauthorized.
You can simply respond with res.status(401).send('Logged out')
or
app.get('/logout', function (req, res) {
res.status(401).send('Logged out')
//or res.status(401).end() if you don't want to send any message
});
I've confirmed that redirecting the user to a /logout page with an http code 401 and html with <a> element links to /login works.