Get JWT token in NextJS API - oauth-2.0

I created a NextJS application integrated with Amazon Cognito. I have a landing page that is using the Amplify Auth API (not the components). Now I need to call an external API to do CRUD operations. What's the best way to do this in NextJS?
I'm thinking I'll create an API in NextJS that will forward the request to the actual external REST API. But my problem is I'm not able to get the JWT Token on the API, since it's a backend code.
A code like this:
Auth.currentSession().then(data => console.log(data.accessToken.jwtToken));
Obviously won't work:
[DEBUG] 20:42.706 AuthClass - Getting current session
[DEBUG] 20:42.706 AuthClass - Failed to get user from user pool
[DEBUG] 20:42.707 AuthClass - Failed to get the current user No current user
(node:20724) UnhandledPromiseRejectionWarning: No current user
How can I get the token in the API?

I have resolved this problem by using the aws-cognito-next library.
Following the documentation from https://www.npmjs.com/package/aws-cognito-next, I have created an auth utility:
import { createGetServerSideAuth, createUseAuth } from "aws-cognito-next";
import pems from "../../pems.json"
// create functions by passing pems
export const getServerSideAuth = createGetServerSideAuth({ pems });
export const useAuth = createUseAuth({ pems });
// reexport functions from aws-cognito-next
export * from "aws-cognito-next";
The pem file was generated by issuing the command (needless to say, you must configure an Amazon Cognito service first):
yarn prepare-pems --region <region> --userPoolId <userPoolId>
And finally, in the NextJs API:
import {getServerSideAuth} from "../../src/utils/AuthUtils"
export default async (req, res) => {
const initialAuth = getServerSideAuth(req)
console.log("initialAuth ", initialAuth)
if (initialAuth) {
res.status(200).json({status: 'success'})
} else {
res.status(400).json({status: 'fail'})
}
}

A simple method is to enable ssrContext in your app and Amplify will provide the user credentials to your api
on the frontend eg _app.tsx (or app.js)
import Amplify, { Auth, API } from "aws-amplify";
import awsconfig from "../src/aws-exports";
Amplify.configure({...awsconfig, ssr: true});
Then in the api you can simply get the currently authenticated cognito user
eg api/myfunction.tsx (or js)
import Amplify, { withSSRContext } from "aws-amplify";
import awsExports from "../../src/aws-exports";
Amplify.configure({ ...awsExports, ssr: true });
/* #returns <CognitoUser>,OR null if not authenticated */
const fetchAuthenticatedUser: any = async (req: NextApiRequest) => {
const { Auth } = withSSRContext({ req });
try {
let user = await Auth.currentAuthenticatedUser();
return user;
} catch (err) {
return null;
}
}

Related

Next.js with SSR: How to access cookies to retrieve a JWT and then make a post request with it

Explanation of my problem
So I am currently on a project of my traineeship that requires me to make a small app using Redux to manage the state of the app itself and TanStack Query (a.k.a. React Query v4) to manage asynchronous data from API calls
I am currently using Next.js with Server-Side Rendering (SSR)
And I have a big issue at the moment with one of the pages
So when the user logs in, they're redirected to their profile page, and I want to make a post request with the JSON Web Token stored in cookies to retrieve their info such as their first name and last name
What I did
I used the Next.js function getServerSideProps to make a POST request with the JWT, but because my app uses SSR. I do not have access to cookies and the JWT is stored inside cookies, but I cannot have access to client-side information until the component is fully mounted, also the app crashes when reloading because of that
I used the native React hook useEffect, I declared the variable with the value of the JWT since now I have access to the cookies, but now I cannot use the TanStack Query hook useMutation because you cannot use hooks inside other hooks
(Current implementation) I used a similar approach, but this time declared the JWT variable as undefined along with the constant using the useMutation outside the useEffect and added the JWT variable inside the array of dependencies of the hook, then I retrieved changed the value of the variable to contain the JWT and made a POST request but the post request fails
Here's the code of my current implementation
//React
import { useEffect, useState } from "react";
//Next
import Head from "next/head";
import { NextRouter, useRouter } from "next/router";
//Components
import AccountCard from "#/components/AccountCard/AccountCard";
import Button from "../../components/Button/Button";
//Utils
import { log } from "../../utils/functions/helper-functions";
import { savingsData } from "../../utils/variables/savings-data";
import CookieService from "#/utils/services/cookies.service";
import ApiService from "#/utils/services/api.service";
//Redux
//React-Redux
import { useSelector } from "react-redux";
import { useMutation } from "#tanstack/react-query";
//This is the page of the user
/**
* User page
*
* Route: `/profile/`
* */
export default function Profile(): JSX.Element {
// log({ jsonWebToken });
//We IMPORT the value of the logging state of the user when logging in
const userIsLoggedIn: boolean = useSelector((state: any) => {
return state.isLoggedIn;
});
//We're going to use the router hook to get the current to redirect the user
//if they're not logged in
const router: NextRouter = useRouter();
[...]
let jsonWebToken: string | undefined = undefined;
//We make the POST request
const apiService: ApiService = new ApiService();
const userProfileMutation = useMutation({
mutationFn: (jwt: string) => {
return apiService.postProfile(jwt);
},
onMutate: () => {},
onSuccess: (data, variables) => {
log("SUCCESS, USER INFOS:", data);
},
onError: () => {
log("FAILED TO RETRIEVE USER INFOS");
},
});
//We cannot use the push() method of the router to redirect the user to the sign-in page
//if the user isn't logged in because of the SSR (push is client side only)
useEffect(() => {
//If the user isn't logged in we redirect them to the sign-in page
const userIsNotLoggedIn: boolean = !userIsLoggedIn;
if (userIsNotLoggedIn) {
router.push("/sign-in/");
}
//We recover the jwt inside the browser"s cookies
const cookieCreator: CookieService = new CookieService();
//We initialise it
jsonWebToken = cookieCreator.getCookieByName("jwt")?.value;
log(jsonWebToken);
//#ts-ignore
userProfileMutation.mutate(jsonWebToken);
}, [jsonWebToken]);
return (
<>...</>
);
}
So I'd be very grateful if somebody was able to help me with this issue

Getting List of YouTube Channel Subscriptions using YouTube Data API V3 in JavaScript

I have been trying to get the list of subscriptions of my channel but unfortunately I get errors every time I run my code, I am describing each step below:
Step 1: I created this channel: My YouTube Channel
Step 2: I enabled the YouTube Data API V3 in Google Developer Console
Step 3: I created API Key and Google OAuth 2.0 Client ID, you can see the following screenshot:
Step 4: I checked the YouTube API Reference and checked some parameters here and got a successful response with all the subscriptions of my channel: YouTube API Reference for my Channel
Step 5: I copied the following code from the YouTube API Reference and placed my own API Key and Google OAuth 2.0 Client ID after I got a successful response for my channel:
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.subscriptions.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/code-samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.subscriptions.list({
"part": [
"subscriberSnippet,contentDetails"
],
"channelId": "UCLlE_JEV7I0pQ7fhY4BIrrQ"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});
Step 6: Then I added the following buttons in my HTML code:
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
Step 7: When I execute the code, I get the following error messages:
Error 1:
"You have created a new client application that uses libraries for user authentication or
authorization that will soon be deprecated. New clients must use the new libraries instead;
existing clients must also migrate before these libraries are deprecated. See the [Migration
Guide](https://developers.google.com/identity/gsi/web/guides/gis-migration) for more
information."
Step 8: Then I click the authorize and load button and sign in to my channel and allow any requested rights. After that, when I click the execute button, then I get the following error:
"The requester is not allowed to access the requested subscriptions."
This is worth mentioning that this is my own channel, I login when required and I allow any rights that are requested. I also use my own Google Developer Console account, my own API Key and my own OAuth 2.0 Client ID. I have enabled the YouTube Data API V3 and I have set up everything properly. I can get the proper result from the YouTube API reference but I can't get it using JS.
Any help is appreciated in advance.
error one.
You have created a new client application that uses libraries for user authentication or
authorization that will soon be deprecated. New clients must use the new libraries instead;
existing clients must also migrate before these libraries are deprecated. See the Migration
Guide for more
information.
The code you are using is using the old google sign-in. You need to change this and use the new Google authorization library Authorizing for Web
Error two:
The requester is not allowed to access the requested subscriptions.
This error is a little harder to understand. First off when the authorization request pops up it should be asking you to pick a user and then a channel Make sure you select the channel that maps to the channel id you are selecting UCLlE_JEV7I0pQ7fhY4BIrrQ The YouTube data api is channel based you only have access to the single channel.
You are also using the "https://www.googleapis.com/auth/youtube.readonly" scope and the subscriptions list method documentation says it needs https://www.googleapis.com/youtube/v3/subscriptions which doesnt exist so I used https://www.googleapis.com/auth/youtube, but i would expect a different error message if this was the issue.
Notes:
I login when required and I allow any rights that are requested.
Make sure its to the correct channel.
I also use my own Google Developer Console account, my own API Key and my own OAuth 2.0 Client ID. I have enabled the YouTube Data API V3 and I have set up everything properly.
This has nothing to do with your access the client id, and api key just identify your application to Google they dont grant it access to anything. Thats what authorization is doing.
YouTube data api QuickStart for Authorizing for Web
Here is my QuickStart for this api.
<!DOCTYPE html>
<html>
<head>
<title>YouTube Data API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>YouTube Data API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '[Redacted]';
const API_KEY = '[Redacted]';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/youtube';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listSubscriptions();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
/**
* Print metadata for first 10 Albums.
*/
async function listSubscriptions() {
let response;
try {
response = await gapi.client.youtube.subscriptions.list({
'pageSize': 10,
'part' :[ "snippet,subscriberSnippet,contentDetails" ],
"channelId": "UCyqzvMN8newXIxyYIkFzPvA",
'fields': 'items(id,snippet(title))',
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const subscriptions = response.result.items;
if (!subscriptions || subscriptions.length == 0) {
document.getElementById('content').innerText = 'No subscriptions found.';
return;
}
// Flatten to string to display
const output = subscriptions.reduce(
(str, subscription) => `${str}${subscription.snippet.title} (${subscription.id}\n`,
'albums:\n');
document.getElementById('content').innerText = output;
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>

get access_token from next_auth to use it with googleapis

How to get access_token from next_auth to use it with googleapis,
lets say i am creating a crud app that store the data in google drive, I am using nextjs and next-auth for OAuth implementation for google. i found this blog so i implemented it. but it logs undefined.
src/pages/api/auth/[...nextauth].ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import jwt from 'next-auth/jwt'
const secret = process.env.SECRET
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
authorization:{
params:{
scope:"openid https://www.googleapis.com/auth/drive.file"
}
}
}),
],
secret: process.env.SECRET,
callbacks: {
jwt: ({token, user, account, profile, isNewUser})=> {
console.log({token,user,account,profile})
if (account?.accessToken) {
token.accessToken = account.accessToken;
}
return token;
},
session: async ({session, user,token}) => {
session.user = user;
session.token = token;
return session
}
},
});
and I created a route with nextjs to get the access token
import {getToken,decode} from 'next-auth/jwt'
const handler = async(req, res)=> {
const secret = process.env.SECRET
const token = await getToken({ req, secret });
const accessToken = token.accessToken;
console.log(accessToken)
}
export default handler
any help would be great. thanks
the google's token is stored in account.access_token not account.accessToken. so the jwt callback must be
callbacks: {
jwt: ({token, account })=> {
if (account?.access_token) {
token.access_token = account.access_token;
}
return token;
},
},
and it is better not to expose tokens on clients side which I done in session callback. it is insecure.
As stated in the documentation, you must forward any data you want to be available in the token, such is your accessToken value:
The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token through the jwt() callback, you have to explicitly forward it here to make it available to the client.
So, you just have to add this to your session callback:
session.accessToken = token.accessToken;

React native app through Expo, getting firestore permission error:

This is my first post here so please let me know if I'm not posting this correctly.
I keep getting the following error in the debug logs of my react native Expo app on the iOS simulator when I have an authenticated user trying to retrieve a firestore document:
FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
Here is firebase.js config file:
import "firebase/firestore";
import "firebase/storage";
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: ... //removed for this post, but it is correct and validated
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
export { auth };
export default db;
Here is my App.js:
import React, { useEffect, useState } from 'react';
import db, { auth } from './firebase';
const getUserData = async(uid) => {
try {
const doc = await db.collection('users').doc(uid).collection('info').doc(uid).get();
if (doc.exists) {
console.log(doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No user info was found for the authenticated user");
}
} catch(err) {
console.log(err);
}
};
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
if (authUser) {
//user is logged in
getUserData(authUser.uid); //retrieve the user's profile data
} else {
//user is logged out
auth.signOut();
}
});
}, []);
My security rules shouldn't be the problem because it works for my web react app with the same logic and user, and the get request is only sent when there is a uid because the user is authenticated. I've printed out the uid after onAuthStateChanged and it is the correct uid.
//Security Rules in Firestore
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedInAndSameUser(uid) {
return request.auth != null && request.auth.uid == uid;
}
match /users/{uid} {
allow read: if request.auth != null;
match /private/{privateId} {
allow read: if signedInAndSameUser(privateId);
}
}
I've seen similar posts that recommended to downgrade to firebase#4.6.2 but I also ran into issues and couldn't get it to work. I'm wondering if firebase still hasn't fixed this issue even after version 8 (In react native app (through Expo) using firestore permissions - request.auth is always null)
This is my current firebase and expo version in my package.json:
//package.json
"expo": "~41.0.1",
"firebase": "8.2.3",
Thank you so much if you can help, I've been stuck on this issue for many hours and can't seem to understand why this works in my react.js web app, but the same logic, user, and security rules won't work in my react native Expo iOS app.

Meteor acounts add info from Twitter accounts

I'm trying to figure out how I can add additional information from a user's Twitter account to the created account on a Meteor installation.
In particular I am trying to access the user's bio via Twitter Api v 1.1 and am not successful in doing so.
Therefore I am trying to extend Accounts.onCreateUser(function(options,user) {}); with the Twitter bio. How do I do that? And then access this data from a template?
Here's a perfect answer for returning data from Github, however I've had trouble porting this approach over to Twitter as the authenticating service: Meteor login with external service: how to get profile information?
You could do it on this way:
Accounts.onCreateUser(function (options, user){
user.profile = options.profile || {};
//Twitter returns some useful info as the username and the picture
if(user.services.twitter){
user.profile.picture= user.services.twitter.profile_image_url_https;
user.profile.username= user.services.twitter.screenName;
}
return user;
});
For getting the data from the Twitter API I´m using the node package oauth:
OAuth = Npm.require('oauth');
oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
'consumerKey',
'secretKey',
'1.0A',
null,
'HMAC-SHA1'
);
getTwitterUserData: function (id) {
var accountUser = AccountsUserCollection.findOne({_id: id});
var url = "https://api.twitter.com/1.1/users/show.json?screen_name="+accountUser.screen_name;
oauth.get(url, 'accessToken', 'accessSecret', function (err, data, response) {
if(err){
console.log(err);
}
if(data){
Fiber(function () {
AccountsUserCollection.update({_id: accountUser._id}, {$set: {dataTwitter: JSON.parse(data)}});
}).run();
}
if(response){
Log.info(response);
}
});
}

Resources