next-auth.js with next.js middleware redirects to sign-in page after successful sign-in - next.js

I use next-auth.js with Google as my login provider and Django as my backend. To protect pages in next.js, I am trying to integrate next-auth.js with next.js middleware. Reference link
The issue I have is when the user is logged out, the middleware correctly routes to the login page. But after successful login, the user is redirected to the login page again. What am I missing?
middleware.js
export { default } from "next-auth/middleware"
export const config = { matcher: ["/jobs/:path*", "/accounts/:path*", "/profile/:path*", "/uploads/:path*"] }
/pages/api/auth/[...nextauth.js]
import axios from "axios";
import NextAuth from "next-auth"
import Google from "next-auth/providers/google";
import { isJwtExpired } from "../../../constants/Utils";
async function refreshAccessToken(token) {
try {
const response = await axios.post(
process.env.NEXT_PUBLIC_BACKEND_BASE + "/api/auth/token/refresh/", {
refresh: token.refreshToken
});
const { access, refresh } = response.data;
return {
...token,
accessToken: access,
refreshToken: refresh,
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshTokenError"
}
}
}
export default NextAuth({
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
access_type: "offline",
response_type: "code",
scope:'openid profile email'
}
}
}),
],
callbacks: {
async jwt({ token, user, account}) {
// Initial sign in
if (account && user) {
if (account.provider === "google") {
const { access_token: accessToken } = account;
try {
// make a GET request to the DRF backend
const response = await axios.get(
process.env.NEXT_PUBLIC_BACKEND_BASE + "/api/auth/register-by-token/google-oauth2/",
{
params:
{
access_token: accessToken
}
}
);
const { access, refresh } = response.data;
token = {
...token,
accessToken: access,
refreshToken: refresh,
};
return token
} catch (error) {
console.log(error)
return {
...token,
error: "NewUserTokenError"
}
}
}
return {
...token,
error: "InvalidProviderError"
}
}
if (isJwtExpired(token.accessToken)) {
return refreshAccessToken(token)
} else {
return token
}
},
async session({ session, token }) {
session.accessToken = token.accessToken
session.refreshToken = token.refreshToken
session.error = token.error
return session
}
}
})

Upgrading next-auth.js to 4.7.0 with next.js at 12.2.0 fixed it for me.

I've run into the same problem and I was able to get it working correctly by disabled prefetching on the <Link prefetch={false} href={'/protected-route'}/> component associated with the protected pages in the application. I think that the prefetched version is cached and, upon successful singIn(), the cached version is served.
I hope it helps!

In nextjs 11.1.4 and NextAuth 4.18.8 this problem still persist
i fixed issue like this.
import { withAuth } from "next-auth/middleware"
// i used advanced middleware configuration
export default withAuth(
function middleware(req) {
// some actions here
},
{
callbacks: {
authorized: ({ token }) => {
// verify token and return a boolean
return true
},
},
}
)
export const config = { matcher: ["/jobs/:path*", "/accounts/:path*", "/profile/:path*", "/uploads/:path*"] }

Related

Is it possible to add more scopes to NextAuth provider during session?

I am currently using NextAuth to signIn in my application, and want to add more scopes into it while the user is already signed in so I can use the Google Fit API.
I've been reading the documentation of NextAuth and doing some research but did not find anything helpful for the current NextAuth v4 in this scope situation.
My current Google configuration:
import NextAuth from 'next-auth';
import GoogleProvider from "next-auth/providers/google"
const GOOGLE_AUTHORIZATION_URL =
'https://accounts.google.com/o/oauth2/v2/auth?' +
new URLSearchParams({
prompt: 'consent',
access_type: 'offline',
response_type: 'code'
})
export default NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: GOOGLE_AUTHORIZATION_URL,
}),
],
callbacks: {
async jwt({ token, user, account }) {
// Initial sign in
if (account && user) {
return {
accessToken: account.access_token,
accessTokenExpires: Date.now() + account.expires_in * 1000,
refreshToken: account.refresh_token,
user
}
}
// Return previous token if the access token has not expired yet
if (Date.now() < token.accessTokenExpires) {
return token
}
// Access token has expired, try to update it
return refreshAccessToken(token)
},
async session({ session, token }) {
session.user = token.user;
session.accessToken = token.accessToken
session.error = token.error
return session
}
},
jwt: {
secret: process.env.NEXTAUTH_JWT_SECRET,
},
secret: process.env.NEXTAUTH_SECRET,
})
async function refreshAccessToken(token) {
try {
const url =
"https://oauth2.googleapis.com/token?" +
new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: token.refreshToken,
})
const response = await fetch(url, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
})
const refreshedTokens = await response.json()
if (!response.ok) {
throw refreshedTokens
}
return {
...token,
accessToken: refreshedTokens.access_token,
accessTokenExpires: Date.now() + refreshedTokens.expires_at * 1000,
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshAccessTokenError",
}
}
}
My current code is working just fine, so I just need the scopes to authorize and use the Google Fitness API.
Actually made it work, created a file called add_scopes.js inside pages/api/auth/
export default (req, res) => {
if (req.method === 'POST') {
// construct the authorize URL with additional scopes
const scopes = 'openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/fitness.activity.read https://www.googleapis.com/auth/fitness.location.read'
const redirectUri = process.env.GOOGLE_CALLBACK_URL
const clientId = process.env.GOOGLE_CLIENT_ID
const authorizationUrl = `https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&access_type=offline&response_type=code&scope=${scopes}&redirect_uri=${redirectUri}&client_id=${clientId}`
// send the authorization URL to the client
res.json({ authorizationUrl });
} else {
res.status(405).end(); // Method Not Allowed
}
}
then made a button to call this api route:
import { useCallback } from 'react';
import { Button } from 'react-bootstrap';
const AddScopesButton = ({scopes=scopes}) => {
const isAuthorized = scopes.includes("https://www.googleapis.com/auth/fitness.activity.read") && scopes.includes("https://www.googleapis.com/auth/fitness.location.read")
const handleClick = useCallback(async () => {
try {
const res = await fetch("/api/auth/add_scopes", { method: "POST" });
const json = await res.json()
if (res.ok) {
window.location.href = json.authorizationUrl;
} else {
throw new Error(res.statusText);
}
} catch (error) {
console.error(error);
}
}, []);
return (
<>
{!isAuthorized && (
<Button className='mt-2' onClick={handleClick}>Add Scopes</Button>
)}
{isAuthorized && <span>Authorized</span>}
</>
);
};
export default AddScopesButton;
The only problem is if you signOut and signIn back in you need to get the authorization again, would really like to know if there is a way to save the accessToken/scopes that were authorized.

Axios getStore is undefined in NextJs api calls. (Redux, NextJs, Jwt)

I am trying to set up authentication for a project. Once a user signs up for our app they get sent to our home page with an id in the query. This id then gets used to submit user and then the jwt token gets saved inside redux state.
All our calls now go through an axios client where the jwt token is passed on every request. The token gets read with store.getState(injectStore)
This all works fine inside getserversideProps, but the issue comes in when using calls on the frontend that goes through NextJs built in 'pages/api' folder. Any calls inside those folders causes the store.getState() to be undefined. I do not understand why since it uses the exact same client as geserversideProps.
Example GetServersideProps(working)
try {
const response = await serverApiClient.get('v1/config');
return {
props: {
},
};
} catch ({ error: { statusCode = 500, message = 'Internal Server Error' } }) {
if (statusCode === 401) {
return {
redirect: {
permanent: false,
destination: '/',
},
};
}
throw new Error(message as string);
}
};
Example Frontend bff call(not working)
try {
// Call below get sent to next built in api
const players = await apiClient.get(`/defenders?sortBy=${statId}&team_id=${teamShortName}`);
return players;
} catch (error) {
return { error };
}
};
export default async function handler(req: NextApiRequest) {
console.log('Start request')
try {
const { sortBy, team_id: teamId } = req.query;
const response = await serverApiClient.get(`/v1/players/picks?position=DEF&sort_by=${sortBy}&team_id=${teamId}`);
Api Client
mergeConfigs(
params: Record<string, string>,
headers: Record<string, string>,
configs: Record<string, string>,
): AxiosRequestConfig {
const defaultConfigs = ApiClient.getDefaultConfigs();
*const token = store?.getState()?.jwtToken?.value*
//ISSUE ABOVE - This store .getState() is only undefined in nextJS api folder calls.
return {
...defaultConfigs,
...configs,
params,
headers: {
...defaultConfigs.headers,
...headers,
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
};
}
get(
uri: string,
params = {},
headers = {},
configs = {},
): Promise<AxiosResponse | any> {
return this.client
.get(uri, this.mergeConfigs(params, headers, configs))
.then((response) => {
return (response.data ? response.data : response);
})
.catch((error) => {
const errorObject = {
error: error?.response?.data,
};
throw Object.assign(errorObject);
});
}
If anyone has some advice on why that getStore is undefined in frontend-to-backend calls please assist. Thanks all!

How to redirect using `getServerSideProps` with props in Next.js?

After a user signs in, I use router.push() to redirect the user to their profile page. I am using getServerSideProps() for authentication right now. When the redirect happens, the props don't seem to be fetched and I have to refresh the browser myself to call gSSR. Is this behavior normal or is there a way to fix it?
Demonstration - Updated
login.js
import {useRouter} from 'next/router';
export default function Login({user}) {
const router = useRouter();
// invoked on submission
async function submitLoginForm(email, password) {
const user = await signIn(email, password)
const username = await getUsernameFromDB(user);
router.push("/" + username);
}
return ( ... );
}
export async function getServerSideProps({req}) {
const user = await getUserFromCookie(req);
if(user === null) {
return {
props: {}
}
}
return {
redirect: {
destination: `/${user.username}`,
permanent: false
}
}
}
[username].js
export default function Profile({user, isUser}) {
// Use isUser to render different interface.
return ( ... );
}
export async function getServerSideProps({params, req}) {
// The username of the path.
const profileUsername = params.username
// Current user.
const user = await getUserFromCookie(req);
...
if(user !== null) {
return {
props: {
user: user,
isUser: user !== null && profileUsername === user.username
}
}
}
return {
notFound: true
}
}
The cookie is set in the _app.js using the Supabase auth sdk.
function MyApp({Component, pageProps}) {
supabase.auth.onAuthStateChange( ( event, session ) => {
fetch( "/api/auth", {
method: "POST",
headers: new Headers( { "Content-Type": "application/json" } ),
credentials: "same-origin",
body: JSON.stringify( { event, session } ),
} );
} );
return (
<Component {...pageProps} />
);
}
I would recommend that you update your _app.js like that:
import { useEffect } from 'react';
function MyApp({ Component, pageProps }) {
// make sure to run this code only once per application lifetime
useEffect(() => {
// might return an unsubscribe handler
return supabase.auth.onAuthStateChange(( event, session ) => {
fetch( "/api/auth", {
method: "POST",
headers: new Headers( { "Content-Type": "application/json" } ),
credentials: "same-origin",
body: JSON.stringify( { event, session } ),
});
});
}, []);
return <Component {...pageProps} />;
}
Also, please make clear what is happening. E.g. my current expectation:
Not authenticated user opens the "/login" page
He does some login against a backend, that sets a cookie value with user information
Then router.push("/" + username); is called
But the problem now: On page "/foo" he sees now the Not-Found page instead of the user profile
Only after page reload, you see the profile page correctly
If the above is correct, then it is possible the following line is not correctly awaiting the cookie to be persisted before the navigation happens:
const user = await signIn(email, password)
It could be that some internal promise is not correctly chained/awaited.
As an recommendation, I would log to the console the current cookie value before calling the router.push to see if the cookie was already saved.

Get supabase `user` server side in next.js

I am attempting to get the current logged in supabase user while server side.
I have attempted to use const user = supabase.auth.user(); but I always get a null response.
I have also attempted const user = supabase.auth.getUserByCookie(req) but it also returns null. I think because I am not sending a cookie to the api when calling it from the hook.
I have tried passing the user.id from the hook to the api but the api is not receiving the parameters.
I also attempted this approach but the token is never fetched. It seems to not exist in req.cookies.
let supabase = createClient(supabaseUrl, supabaseKey);
let token = req.cookies['sb:token'];
if (!token) {
return
}
let authRequestResult = await fetch(`${supabaseUrl}/auth/v1/user`, {
headers: {
'Authorization': `Bearer ${token}`,
'APIKey': supabaseKey
}
});
`
Does anyone know how to get the current logged in user in server side code?
If you need to get the user in server-side, you need to set the Auth Cookie in the server using the given Next.js API.
// pages/api/auth.js
import { supabase } from "../path/to/supabaseClient/definition";
export default function handler(req, res) {
if (req.method === "POST") {
supabase.auth.api.setAuthCookie(req, res);
} else {
res.setHeader("Allow", ["POST"]);
res.status(405).json({
message: `Method ${req.method} not allowed`,
});
}
}
This endpoint needs to be called every time the state of the user is changed, i.e. the events SIGNED_IN and SIGNED_OUT
You can set up a useEffect in _app.js or probably in a User Context file.
// _app.js
import "../styles/globals.css";
import { supabase } from '../path/to/supabaseClient/def'
function MyApp({ Component, pageProps }) {
useEffect(() => {
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
handleAuthChange(event, session)
if (event === 'SIGNED_IN') {
// TODO: Actions to Perform on Sign In
}
if (event === 'SIGNED_OUT') {
// TODO: Actions to Perform on Logout
}
})
checkUser()
return () => {
authListener.unsubscribe()
}
}, [])
return <Component {...pageProps} />;
}
async function handleAuthChange(event, session) {
await fetch('/api/auth', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
credentials: 'same-origin',
body: JSON.stringify({ event, session }),
})
}
export default MyApp;
You can now handle this user with a state and pass it to the app or whichever way you'd like to.
You can get the user in the server-side in any Next.js Page
// pages/user_route.js
import { supabase } from '../path/to/supabaseClient/def'
export default function UserPage ({ user }) {
return (
<h1>Email: {user.email}</h1>
)
}
export async function getServerSideProps({ req }) {
const { user } = await supabase.auth.api.getUserByCookie(req)
if (!user) {
return { props: {}, redirect: { destination: '/sign-in' } }
}
return { props: { user } }
}
Here's a YouTube Tutorial from Nader Dabit - https://www.youtube.com/watch?v=oXWImFqsQF4
And his GitHub Repository - https://github.com/dabit3/supabase-nextjs-auth
supabase have a library of helpers for managing auth for both client- and server-side auth and fetching in a couple of frameworks including Next.js: https://github.com/supabase/auth-helpers and appears to be the recommended solution for similar problems based on this thread: https://github.com/supabase/supabase/issues/3783
This is how I'm using it in an API handler, but provided you have access to req, you can access the user object this way:
import { supabaseServerClient } from '#supabase/auth-helpers-nextjs';
const { user } = await supabaseServerClient({ req, res }).auth.api.getUser(req.cookies["sb-access-token"]);
Note that you will need to use the helper library supabaseClient and supabaseServerClient on the client and server side respectively for this to work as intended.
I was following a tutorial today and was having a similar issue and the below is how i managed to fix it.
I've got this package installed github.com/jshttp/cookie which is why i'm calling cookie.parse.
Supabase Instance:
`//../../../utils/supabase`
import { createClient } from "#supabase/supabase-js";
export const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_KEY
);
In my case this was my API page:
import { supabase } from "../../../utils/supabase";
import cookie from "cookie";
import initStripe from "stripe";
const handler = async (req, res) => {
const { user } = await supabase.auth.api.getUserByCookie(req);
if (!user) {
return res.status(401).send("Unathorized");
}
const token = cookie.parse(req.headers.cookie)["sb-access-token"];
supabase.auth.session = () => ({
access_token: token,
});`
const {
data: { stripe_customer },
} = await supabase
.from("profile")
.select("stripe_customer")
.eq("id", user.id)
.single();
For anyone who tries to figure out how to get the user server side with the new #supabase/auth-helpers-nextjs, Michele gave the answer.
Just a note: If you're trying to get the user on nextJs's Middleware, instead of:
... req.cookies["sb-access-token"]
You have to use: req.cookies.get('sb-access-token')
For example:
import { supabaseServerClient } from '#supabase/auth-helpers-nextjs';
const { user } = await supabaseServerClient({ req, res }).auth.api.getUser(req.cookies.get('sb-access-token'))
UPDATE: 2023. Available now on Supabase Docs here
import { createServerSupabaseClient } from '#supabase/auth-helpers-nextjs'
export default function Profile({ user }) {
return <div>Hello {user.name}</div>
}
export const getServerSideProps = async (ctx) => {
// Create authenticated Supabase Client
const supabase = createServerSupabaseClient(ctx)
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession()
if (!session)
return {
redirect: {
destination: '/',
permanent: false,
},
}
return {
props: {
initialSession: session,
user: session.user,
},
}
}

Can't sign in with correct Email address and Password with Firebase

I create one web App for graduation research (developed with Vue.js, vue-router). I'm using Firebase Authentication to sign in. Even though using the correct Email Address and password, I can't sign in and the site redirect from 'localhost:8080/signin' to 'localhost:8080/signin?' .
This is developed with Vue(2.6.10) and firebase.
(ellipsis)
input(type="text" placeholder="your#email.com" v-model="email")#MailAddress
(ellipsis)
input(type="password" placeholder="password" v-model="password")#Password
(ellipsis)
import firebase from "firebase";
export default {
name: "Signin",
data() {
return {
email: "",
password: ""
};
},
methods: {
signIn() {
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(
() => {
alert("Success");
this.$router.push("/");
},
err => {
alert(err.message);
}
);
}
}
};
I expect to redirect to 'localhost:8080/'
This works for me.
In my Vue component:
import firebase from '../database';
async signIn () {
let result = await firebase.signIn(this.email, this.password);
if (result.message) {
this.error = result.message;
} else {
// Go to your route
}
}
In my database file:
const database = firebase.initializeApp(config);
database.signIn = async (email, password) => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
return true;
} catch (error) {
return error;
}
};

Resources