How to authorize user using next auth with nodejs server? - node.js

I am using next auth for user authentication in my nextjs app, but my end points are on nodejs server (while next auth logic is in api/auth/[...nextauth] file). How can I verify that the user who sent the request from nextjs app to my nodejs server is authorized or not.
Is there a way to send and verify jwt token set by next auth to node js backend and see if user is authenticated or not?

It should be technically possible. For example, you can pass the JWT created by NextAuth to the Node.JS APIs via the Authorization header and decode the JWT using the value of NEXTAUTH_SECRET.
const jwt = require("jsonwebtoken");
const decode = jwt.verify(token, "secret");

Related

Delegate authentication token from react app to express app with OpenID and passportjs

I am using the OpenID client to authenticate the user, what I would like to do is call a protected route on an express API.
I am trying to share the authorization cookie obtained with the react app with OpenID, and the xenter image description here
I tried:
simply passport.authenticate(), with the openID strategy, but does redirection which isnt necessary
Not sure if this is the correct way but, this is how I kinda did it:
const user = await auth0Client.getUser();
// Attach token
const accessToken = await auth0Client.getTokenSilently();
axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
Then I just used the passport JWT strategy combined with jwks-rsa library to obtain the secret.

How does cognitoidentityserviceprovider.getUser() work?

My questions is regarding AWS Cognito SDK. My front-end authenticates the user with amplify /cognito and sends the token in the header to my backend.
I have successfully used cognitoidentityserviceprovider.getUser() to get user attributes on my backend nodejs app, but without any permissions!
I am using a restricted user with only S3 and SES permissions on my API, but I am just surprised, the getUser() call just decode the JWT token without any authorisation? and if so, can anyone decode all user attributes from my jwt token using aws-sdk?
I also removed the API key entirely on the backend, just to see and it was still able get the user object successfully. Is this not a security risk?
Code:
const aws = require('aws-sdk');
var provider = new aws.CognitoIdentityServiceProvider();
const user = await provider.getUser( {AccessToken: jwtToken}).promise();
return user;

How can i persist users on my web application with my Node/Express and Firebase backend

Im currently creating a web application using the react/node/express on top of firebase.
Im confused as to how I should persist my user on the client side.
Currently I have sign up and login routes on my Node/Express server that are working and they each return a JWT which I then save to local storage and then add to each request header as a Bearer token.
The problem is that the JWT token expires after 1 hour and the user has to sign in again.
How can I fix this and persist the user forever(if they choose) along with avoiding saving the JWT in local storage. I was looking over the docs and found this https://firebase.google.com/docs/auth/web/auth-state-persistence but im not sure how i would use that with my node/express server.
Firebase accepts session cookies so you can simply create a cookie or a header on the /login endpoint of the backend and return the user as a response if you don't want a solution which includes local storage:
resp.cookie('Authorization', 'Bearer ' + token, {httpOnly: true, secure: false});
return resp.status(200).send({user, events});

Firebase - verify session cookie or idtoken

I've got an api where I validate an idToken from firebase, this api is used by a web app and a mobile app.
The web app uses a session token and the mobile app the standard idToken.
As it stands my api correctly validates the standard token from the mobile app using the admin sdk's admin.auth().verifyIdToken() method.
If I pass the session token to this it fails with an iss error
Firebase ID token has incorrect "iss" (issuer) claim
I know I can validate the session token via
admin.auth().verifySessionCookie() method. But I would have to do this in the catch block of the verifyIdToken promise.
Is there a method or way where I can just use one step to validate this token, or is my only option to catch an error from one and then try the other method?

node js JWT get current user

I work on app with an authentication using Node JS, JWT and Sequelize for the API and I'm using React JS / redux for the front part. I'm successfully implemented the login/logout/register parts for the application, but now I need to access to the current_user logged in.
I put a JWT in the localStorage, but I want to have access to the user ID, user email, user name and more informations about my user currently logged in.
Should I use Cookies ? LocalStorage ? Or should I create a currentUser method in my API ?
I'm a bit lost with this, if someone could help me find some usefull resources or advices !
Thank !
If you put that information in the payload of the JWT, then you can get it without decoding on the server or needing the secret, and can therefore put the token in LocalStorage for use whenever. By the spec, a JWT is <headerINfo>.<payloadInfo>.<signature>. So on the client, you can just do:
// given a payload object of { username: 'bob', userid: 1, email: 'bob#example.com' }
const tokenParts = token.split('.');
const encodedPayload = tokenParts[1];
const rawPayload = atob(encodedPayload);
const user = JSON.parse(rawPayload);
console.log(user.username); // outputs 'bob'
Obviously, this info is available to any client that has access to the Token, so you only want to put stuff in the payload that that's OK for.
Storing the token in LocalStorage is fine. If you need to fetch the user details, create an endpoint in your API such as getUser. You can then use jwt.decode(accessToken, JWT SECRET HERE) and return the decoded value (which will be your user) assuming the accessToken is valid.
You can make a middleware if you haven't already that will ensure that user info is always available to those routes that require it:
const auth = jwt({
secret: JWT_SECRET,
userProperty: 'payload',
algorithms: ['HS256']
});
module.exports = auth;
Then you should have req.payload with user details. Alternatively you can check the Authorization property in your headers depending on how you set up your app.
When logging in, server should send token and user data, you can store that data in Redux store. Then simply request data from there. When user reloads page, send API request with JWT token and server should return user data, that you will again put in Redux store.

Resources