Bootstrap

next.js-学习5

15.身份验证

身份验证与授权

在web开发中,身份验证和授权扮演着不同的角色:

•身份验证是为了确保用户是他们所说的那个人。你在用用户名和密码之类的东西来证明你的身份。

•下一步是授权。一旦确认了用户的身份,授权将决定允许他们使用应用程序的哪些部分。

因此,身份验证检查您是谁,授权确定您可以在应用程序中执行什么操作或访问什么。

1.创建登录路由

/app/login/page.tsx

import AcmeLogo from '@/app/ui/acme-logo';
import LoginForm from '@/app/ui/login-form';
import { Suspense } from 'react';
 
export default function LoginPage() {
  return (
    <main className="flex items-center justify-center md:h-screen">
      <div className="relative mx-auto flex w-full max-w-[400px] flex-col space-y-2.5 p-4 md:-mt-32">
        <div className="flex h-20 w-full items-end rounded-lg bg-blue-500 p-3 md:h-36">
          <div className="w-32 text-white md:w-36">
            <AcmeLogo />
          </div>
        </div>
        <Suspense>
          <LoginForm />
        </Suspense>
      </div>
    </main>
  );
}

点击首页登录

在这里插入图片描述
在这里插入图片描述

安装NextAuth.js,NextAuth.js抽象了管理会话、登录和注销以及其他认证方面所涉及的许多复杂性,beta版与Next.js 14+兼容

pnpm i next-auth@beta

生成密钥

# macOS
openssl rand -base64 32
# Windows can use https://generate-secret.vercel.app/32

.env中使用密钥,如果是部署到Vercel,需要更新环境变量,https://vercel.com/docs/projects/environment-variables

AUTH_SECRET=your-secret-key

您可以使用pages选项为自定义登录、注销和错误页面指定路由。这不是必需的,但是通过在pages选项中添加signIn: ‘/login’,用户将被重定向到我们的自定义登录页面,而不是NextAuth.js的默认页面。

创建/auth.config.ts,配置

import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login',
  },
} satisfies NextAuthConfig;

用Next.js中间件保护你的路由,接下来,添加逻辑来保护路由。这将阻止用户访问仪表板页面,除非他们已登录。

/auth.config.ts 中authConfig加入callbacks属性,providers属性

callbacks: {
    //如果访问 /dashboard 且未登录 → 返回 false,阻止访问。
    //如果访问 /dashboard 且已登录 → 允许访问。
    //如果访问非 /dashboard 页面且已登录 → 自动重定向到 /dashboard。
    //其他情况(如未登录访问非 /dashboard 页面)→ 允许访问。
    authorized({ auth, request: { nextUrl } }) {
      //为什么使用 !!auth?.user?
      //在 JavaScript 里,某些值(如 null、undefined、0、""、false)被认为是 "假值" (Falsy values),而对象、数组、非空字符串等是 "真值" (Truthy values)。
      //如果直接写 auth?.user,它可能返回 undefined,但在某些情况下你可能需要明确得到 true 或 false,所以用 !! 强制转换成布尔值。
      //!!auth?.user 用于检查 auth.user 是否存在,并返回 true(已登录)或 false(未登录)。
      //这是 JavaScript 中的惯用写法,常用于权限检查、状态判断等场景。
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false; // Redirect unauthenticated users to login page
      } else if (isLoggedIn) {
        return Response.redirect(new URL('/dashboard', nextUrl));
      }
      return true;
    },
  },
  providers: [], // Add providers with an empty array for now

创建个/middleware.ts文件,在此任务中使用中间件的优点是,在中间件验证身份验证之前,受保护的路由甚至不会开始呈现,从而增强了应用程序的安全性和性能。

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';

export default NextAuth(authConfig).auth;
//排除以 api、_next/static、_next/image 开头的 URL 路径。
//排除以 .png 结尾的图片文件路径。
//其他路径都会匹配,并且会被中间件(可能是身份验证逻辑)处理
export const config = {
  // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
  matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};

bcrypt 依赖一些 Node.js API(比如文件系统、加密等),而 Next.js 的 Middleware 不支持这些 API,所以创建个/auth.ts文件

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
});

/auth.ts中,添加凭证登录

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import Credentials from 'next-auth/providers/credentials';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [Credentials({})],
});

/auth.ts中,添加登录功能

// ...
import { z } from 'zod';//引入
// ...
Credentials({
      async authorize(credentials) {
        const parsedCredentials = z
          .object({ email: z.string().email(), password: z.string().min(6) })
          .safeParse(credentials);
      },
    }),
// ...

/auth.ts中,验证凭证后,再去查数据库用户

// ...
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcryptjs';
import postgres from 'postgres';

const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
 
async function getUser(email: string): Promise<User | undefined> {
  try {
    const user = await sql<User[]>`SELECT * FROM users WHERE email=${email}`;
    return user[0];
  } catch (error) {
    console.error('Failed to fetch user:', error);
    throw new Error('Failed to fetch user.');
  }
}

// ...
//如果parsedCredentials签名成功,使用邮箱和密码登录用户返回
async authorize(credentials) {
    // ...
 if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          const user = await getUser(email);
          if (!user) return null;
        }
        return null;
    // ...

/auth.ts中,调用bcrypt.compare校验密码是否匹配

// ...
      async authorize(credentials) {
        // ...
          if (!user) return null;
          const passwordsMatch = await bcrypt.compare(password, user.password);
          if (passwordsMatch) return user;
        }
        console.log('Invalid credentials');
        return null;
      // ...

2.更新登录表单

/app/lib/actions.ts中,加入authenticate函数

// ...
import { signIn } from '@/auth';
import { AuthError } from 'next-auth';
 
// ...
 
export async function authenticate(
  prevState: string | undefined,
  formData: FormData,
) {
  try {
    await signIn('credentials', formData);
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          return 'Invalid credentials.';
        default:
          return 'Something went wrong.';
      }
    }
    throw error;
  }
}

app/ui/login-form.tsx中,使用React的useActionState来调用服务器操作,处理表单错误,并显示表单的挂起状态

'use client';
// ...
import { useActionState } from 'react';
import { authenticate } from '@/app/lib/actions';
import { useSearchParams } from 'next/navigation';

export default function LoginForm() {
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
  const [errorMessage, formAction, isPending] = useActionState(
    authenticate,
    undefined,
  );
   return (
    <form action={formAction} className="space-y-3">
    // ...
       <input type="hidden" name="redirectTo" value={callbackUrl} />
        <Button className="mt-4 w-full" aria-disabled={isPending}>
          Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
        </Button>
        <div
          className="flex h-8 items-end space-x-1"
          aria-live="polite"
          aria-atomic="true"
        >
          {errorMessage && (
            <>
              <ExclamationCircleIcon className="h-5 w-5 text-red-500" />
              <p className="text-sm text-red-500">{errorMessage}</p>
            </>
          )}
        </div>
 	</div>
   </form>
 );

访问:http://localhost:3000/dashboard/xxx都会跳转到login登录

在这里插入图片描述

3. 注销功能

/ui/dashboard/sidenav.tsx中

// ...
import { signOut } from '@/auth';
// ...
<form
          action={async () => {
            'use server';
            await signOut({ redirectTo: '/' });
          }}
        >
// ...

4. 测试登录

然后再访问http://localhost:3000/dashboard/invoices就能正常显示了。

点击首页的退出,再使用http://localhost:3000/dashboard/invoices请求就会跳转到登录页。

16.添加元数据

  1. 标题元数据:负责显示在浏览器选项卡上的网页标题。这对搜索引擎优化至关重要,因为它可以帮助搜索引擎了解网页的内容。

    <title>Page Title</title>
    
  2. 描述元数据:此元数据提供网页内容的简要概述,通常显示在搜索引擎结果中。

    <meta name="description" content="A brief description of the page content." />
    
  3. 关键字元数据:这些元数据包括与网页内容相关的关键字,帮助搜索引擎索引页面。

    <meta name="keywords" content="keyword1, keyword2, keyword3" />
    
  4. Open Graph元数据:这种元数据增强了网页在社交媒体平台上共享时的表现方式,提供了标题、描述和预览图像等信息。

    <meta property="og:title" content="Title Here" />
    <meta property="og:description" content="Description Here" />
    <meta property="og:image" content="image_url_here" />
    
  5. Favicon元数据:该元数据将Favicon(一个小图标)链接到网页,显示在浏览器的地址栏或选项卡中。

    <link rel="icon" href="path/to/favicon.ico" />
    
  6. 添加元数据,在/public下有2个文件favicon.ico和opengraph-image.jpg,移动到/app下,这样做之后,Next.js将自动识别并使用这些文件作为您的图标和OG图像。您可以通过在开发工具中检查应用程序的元素来验证这一点

  7. /app/layout.tsx中,添加全局的页面标题和描述

    // ...
    import { Metadata } from 'next';
    export const metadata: Metadata = {
      title: 'Acme Dashboard',
      description: 'The official Next.js Course Dashboard, built with App Router.',
      metadataBase: new URL('https://next-learn-dashboard.vercel.sh'),
    };
    // ...
    

    /app/dashboard/invoices/page.tsx中覆盖全局的

    // ...
    import { Metadata } from 'next';
     
    export const metadata: Metadata = {
     title: 'Invoices | Acme Dashboard',
    };
    // ...
    

    /app/layout.tsx中更新模板,这样比如公司名字这种会在所有页面一键替换的

    import { Metadata } from 'next';
     
    export const metadata: Metadata = {
      title: {
        template: '%s | Acme Dashboard',
        default: 'Acme Dashboard',
      },
     description: 'The official Next.js Learn Dashboard built with App Router.',
      metadataBase: new URL('https://next-learn-dashboard.vercel.sh'),
    };
    

    /app/dashboard/invoices/page.tsx中使用

    export const metadata: Metadata = {
      title: 'Invoices',
    };
    

    为这些页面添加标题吧

    /login page.
    /dashboard/ page.
    /dashboard/customers page.
    /dashboard/invoices/create page.
    /dashboard/invoices/[id]/edit page.
    

完整项目地址

https://github.com/hexiaoming123/nextjs-dashboard,当你自己提交后,github会自动打包部署到https://vercel.com/hes-projects-5f35bd0a/nextjs-dashboard/deployments,你自己的https://vercel.com/

next .js还有许多其他特性。它的目的是帮助你建立小的业余项目,你的下一个创业想法,甚至与你的团队大规模的应用程序。

下面是继续探索Next.js的一些资源:

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;