详解Next Auth:自定义邮箱密码登录注册、Github、Notion授权 & Convex集成

最近用NextJS框架做全栈项目做的很顺手,现在想给项目加上登录、注册、鉴权拦截、分角色路由控制等功能,并接入Github、Notion等第三方登录。
可以使用NextJS官方提供的Auth框架实现。

Intro

阅读本篇,你将学会:
1、登录、注册等逻辑,和如何接入第三方(以Github、Notion为例)
2、建立用户、角色等数据模型,存储用户数据
3、公开、私有路由守卫

技术栈

  • NextJs(前端框架) v14.2.3
  • React(前端框架) 18
  • NextAuth(鉴权框架) v5.0.0-beta.18
  • Convex (后端接口 + ORM)

背景知识学习

在开始实现之前,需要知道NextJS中服务端组件和客户端组件的概念。
NextJS中使用”use client“和”use server“标识服务端和客户端组件,客户端运行在浏览器中,服务端运行在服务器端。不标识时,默认为服务端组件。
服务端组件用于异步请求等,负责与服务端交互、请求数据等,客户端组件主要用于和用户交互。React的钩子也有明确的区分,比如useEffect等钩子只能在客户端组件中使用。

实现步骤

代码框架搭建

npx create-next-app@latest  

使用NextAuth(v5版本)

npm install next-auth@beta  

开始之前,需要在环境变量文件.env.local中配置变量

AUTH_SECRET=**********************

Credentials

我们首先实现一个简单的账号密码注册、登录、登出。
参考: Credentials

1.基础配置

在项目根目录下,新建auth.js文件,并写入以下内容:

import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
// Your own logic for dealing with plaintext password strings; be careful!
import {
    saltAndHashPassword } from "@/utils/password"
 
export const {
    handlers, signIn, signOut, auth } = NextAuth({
   
  providers: [
    Credentials({
   
      authorize: async (credentials) => {
   
        let user = null
 
       // logic to salt and hash password
        const pwHash = saltAndHashPassword(credentials.password)
 
        // logic to verify if user exists
        user = await getUserFromDb(credentials.email, pwHash)
 
        if (!user) {
   
          // No user found, so this is their first attempt to login
          // meaning this is also the place you could do registration
          throw new Error("User not found.")
        }
 
        // return user object with the their profile data
        return user
      },
    }),
  ],
})

在根目录下,新建文件middleware.ts

import NextAuth from 'next-auth';

import {
   
DEFAULT_LOGIN_REDIRECT,
apiAuthPrefix,
authRoutes,
publicRoutes,
} from "@/routes"

import {
    auth } from './auth';
export default auth((req) => {
   

const {
    nextUrl } = req;
// console.log("NEXT URL" + nextUrl.pathname)
const isLoggedIn = !!req.auth;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoutes = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
if (isApiAuthRoute) {
   
// DO NOTHING!
return null;

}
if (isAuthRoute) {
   
if (isLoggedIn) {
   
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
} else {
   
return null;
}
}

if (!isLoggedIn && !isPublicRoutes) {
   

return Response.redirect(new URL("/auth/login", nextUrl))

}

})
// invoke the middle ware!

export const config = {
   

matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],

};

routes.ts

// Public Routes
export const publicRoutes = [
"/",
]
// redirect logged in users to /settings
export const authRoutes = [
"/auth/login",
"/auth/register",
]
export const apiAuthPrefix = "/api/auth"
export const DEFAULT_LOGIN_REDIRECT = "/dashboard"

middleware.ts为保留文件名,其中config变量定义了触发中间件方法的匹配规则。该文件中,定义了auth方法的过滤器。
route.ts中定义公开路径、用于鉴权的路径、鉴权接口前缀及默认重定向地址。
在过滤方法中,返回null说明无需执行权限检查。对于公开路径及鉴权接口,无需登录即可访问。登录后,再访问注册和登录页面,会自动重定向到DEFAULT_LOGIN_REDIRECT定义的/dashboard路由中。
配置NextAuth路由:
api/auth/[...nextauth]/route.ts

import {
    handlers } from "@/auth"
export const {
    GET, POST } = handlers

2.注册页面

实现形如下图的注册页面,核心为可提交的表单,包含name、email、password等字段。

image.png

使用zod进行字段的合法性校验。在schemas/index.ts中,定义注册使用的schema:

import * as z from "zod"
export const RegisterSchema = z.object({
   
    email: z.string().email({
   
        message: "Email is Required."
    }),
    password: z.string().min(6,
以下是一个简单的SpringBoot集成SpringSecurity的例子,实现自定义登录授权。 1. 添加依赖 在`pom.xml`文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置SpringSecurity 在`application.properties`文件中添加如下配置: ```properties # 禁用csrf security.enable-csrf=false # 配置自定义登录页面 spring.security.login-form=/login # 配置自定义登录接口 spring.security.login-processing-url=/login ``` 3. 创建自定义UserDetailsService实现类 创建一个实现`UserDetailsService`接口的类`CustomUserDetailsService`,用于从数据库中获取用户信息。在该类中,我们需要注入一个`UserRepository`,用于从数据库中获取用户信息。 ```java @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found with username: " + username); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); } } ``` 4. 创建自定义User实体类和Repository接口 创建一个`User`实体类,用于表示用户信息,并创建一个`UserRepository`接口,用于从数据库中获取用户信息。 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; // getter and setter methods } @Repository public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } ``` 5. 创建自定义授权规则 创建一个实现`GrantedAuthority`接口的类`CustomGrantedAuthority`,用于表示用户的授权角色。在该类中,我们需要定义一个`role`属性,表示用户的角色。 ```java public class CustomGrantedAuthority implements GrantedAuthority { private String role; public CustomGrantedAuthority(String role) { this.role = role; } @Override public String getAuthority() { return role; } } ``` 6. 创建自定义AuthenticationProvider实现类 创建一个实现`AuthenticationProvider`接口的类`CustomAuthenticationProvider`,用于自定义用户的认证和授权规则。在该类中,我们需要注入`UserDetailsService`和`PasswordEncoder`对象,并实现`authenticate()`方法和`supports()`方法。 ```java @Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (userDetails == null) { throw new UsernameNotFoundException("User not found with username: " + username); } if (!passwordEncoder.matches(password, userDetails.getPassword())) { throw new BadCredentialsException("Invalid password"); } Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new CustomGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken(username, password, authorities); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } ``` 7. 创建自定义登录页面和控制器 在`resources/templates`目录下创建一个`login.html`文件,用于自定义登录页面。在`com.example.demo.controller`包下创建一个`LoginController`类,用于处理登录请求。 ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login Page</title> </head> <body> <h3>Login Page</h3> <form action="/login" method="post"> <input type="text" name="username" placeholder="Username" required/><br> <input type="password" name="password" placeholder="Password" required/><br> <input type="submit" value="Login"/> </form> </body> </html> ``` ```java @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/home") public String home() { return "home"; } } ``` 8. 创建自定义授权规则配置类 创建一个实现`WebSecurityConfigurerAdapter`类的`CustomWebSecurityConfigurer`类,用于自定义授权规则。在该类中,我们需要注入`CustomAuthenticationProvider`对象,并重写`configure()`方法。 ```java @Configuration @EnableWebSecurity public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationProvider customAuthenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/home").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } } ``` 9. 运行程序 启动应用程序后,访问`http://localhost:8080/login`,将跳转到自定义登录页面。输入正确的用户名和密码,将跳转到自定义的`home`页面。如果输入错误的用户名或密码,将返回错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值