Я хочу иметь возможность аутентифицировать пользователей с помощью OAuth и защищать конечные точки API с помощью основной аутентификации. Как я могу достичь этого? Моя конфигурация в настоящее время не работает, если я не удаляю основную часть AUTH и исключаю маршруты API из аутентификации/авторизации. В этом случае только аутентификация OAuth работает отлично.import type { NextAuthConfig, Session } from 'next-auth';
import Google from "next-auth/providers/google"
import { SupabaseAdapter } from "@auth/supabase-adapter"
import { NextRequest } from 'next/server';
export const authConfig = {
pages: {
signIn: '/login'
},
callbacks: {
authorized({ auth, request: { nextUrl }} : {auth: null | Session, request: NextRequest}) {
const isLoggedIn = !!auth?.user;
const isOnHomePage = nextUrl.pathname === '/';
if (isOnHomePage) {
if (isLoggedIn) {
return true;
}
return false; // Redirect unauthenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL('/', nextUrl))
}
return true;
}
},
providers: [Google],
adapter: SupabaseAdapter({
url: process.env.SUPABASE_URL!,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
})
} satisfies NextAuthConfig;
< /code>
auth.ts
import NextAuth from "next-auth";
import { authConfig } from './auth.config';
export const { handlers, signIn, signOut, auth } = NextAuth(authConfig)
< /code>
middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import { NextResponse } from 'next/server';
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const url = new URL(req.url);
// Explicitly skip NextAuth API routes and session endpoint
if (url.pathname.startsWith('/api/auth/') || url.pathname === '/api/session') {
return NextResponse.next();
}
if (url.pathname.startsWith('/api/')) {
const authHeader = req.headers.get('authorization') ?? '';
if (!authHeader.startsWith('Basic ')) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
const base64 = authHeader.slice(6);
let decoded = '';
try {
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
decoded = Buffer.from(base64, 'base64').toString('utf-8');
} else if (typeof atob === 'function') {
decoded = atob(base64);
} else {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
} catch (err) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
const [username, password] = decoded.split(':');
const validUsername = process.env.API_BASIC_AUTH_USER;
const validPassword = process.env.API_BASIC_AUTH_PASS;
if (!validUsername || !validPassword || username !== validUsername || password !== validPassword) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
// Basic auth passed — continue to API handler
return NextResponse.next();
}
// Non-API routes: proceed (NextAuth will handle redirects/auth pages)
return NextResponse.next();
});
export const config = {
// apply middleware to API routes and app pages; do NOT use negated matcher entries
matcher: [
'/api/:path*',
'/((?!_next/static|_next/image|.*\\.png$).*)'
],
};
< /code>
Я получаю ошибку следующей в консоли браузера: < /p>
providers.tsx:36 ClientFetchError: Unexpected token '
Подробнее здесь: https://stackoverflow.com/questions/797 ... th-auth-js
Многочисленные методы аутентификации в NextJs с auth.js ⇐ Javascript
Форум по Javascript
-
Anonymous
1755678834
Anonymous
Я хочу иметь возможность аутентифицировать пользователей с помощью OAuth и защищать конечные точки API с помощью основной аутентификации. Как я могу достичь этого? Моя конфигурация в настоящее время не работает, если я не удаляю основную часть AUTH и исключаю маршруты API из аутентификации/авторизации. В этом случае только аутентификация OAuth работает отлично.import type { NextAuthConfig, Session } from 'next-auth';
import Google from "next-auth/providers/google"
import { SupabaseAdapter } from "@auth/supabase-adapter"
import { NextRequest } from 'next/server';
export const authConfig = {
pages: {
signIn: '/login'
},
callbacks: {
authorized({ auth, request: { nextUrl }} : {auth: null | Session, request: NextRequest}) {
const isLoggedIn = !!auth?.user;
const isOnHomePage = nextUrl.pathname === '/';
if (isOnHomePage) {
if (isLoggedIn) {
return true;
}
return false; // Redirect unauthenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL('/', nextUrl))
}
return true;
}
},
providers: [Google],
adapter: SupabaseAdapter({
url: process.env.SUPABASE_URL!,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
})
} satisfies NextAuthConfig;
< /code>
auth.ts
import NextAuth from "next-auth";
import { authConfig } from './auth.config';
export const { handlers, signIn, signOut, auth } = NextAuth(authConfig)
< /code>
middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import { NextResponse } from 'next/server';
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const url = new URL(req.url);
// Explicitly skip NextAuth API routes and session endpoint
if (url.pathname.startsWith('/api/auth/') || url.pathname === '/api/session') {
return NextResponse.next();
}
if (url.pathname.startsWith('/api/')) {
const authHeader = req.headers.get('authorization') ?? '';
if (!authHeader.startsWith('Basic ')) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
const base64 = authHeader.slice(6);
let decoded = '';
try {
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
decoded = Buffer.from(base64, 'base64').toString('utf-8');
} else if (typeof atob === 'function') {
decoded = atob(base64);
} else {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
} catch (err) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
const [username, password] = decoded.split(':');
const validUsername = process.env.API_BASIC_AUTH_USER;
const validPassword = process.env.API_BASIC_AUTH_PASS;
if (!validUsername || !validPassword || username !== validUsername || password !== validPassword) {
return new NextResponse('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Restricted"' },
});
}
// Basic auth passed — continue to API handler
return NextResponse.next();
}
// Non-API routes: proceed (NextAuth will handle redirects/auth pages)
return NextResponse.next();
});
export const config = {
// apply middleware to API routes and app pages; do NOT use negated matcher entries
matcher: [
'/api/:path*',
'/((?!_next/static|_next/image|.*\\.png$).*)'
],
};
< /code>
Я получаю ошибку следующей в консоли браузера: < /p>
providers.tsx:36 ClientFetchError: Unexpected token '
Подробнее здесь: [url]https://stackoverflow.com/questions/79739898/multiple-authentication-methods-in-nextjs-with-auth-js[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия