چگونه در Nest JS GraphQL API یک ویژگی Authentication & Authorization ایجاد کنیم؟

ایجاد یک ویژگی احراز هویت و مجوز در یک NestJS GraphQL API شامل چندین مرحله است. در اینجا یک راهنمای گام به گام آورده شده است:
مرحله 1: یک پروژه NestJS جدید راه اندازی کنید
- Nest CLI را نصب کنید:
npm install -g @nestjs/cli
- یک پروژه جدید ایجاد کنید:
nest new project-name
- به دایرکتوری پروژه بروید:
cd project-name
مرحله 2: بسته های مورد نیاز را نصب کنید
- بسته های لازم را نصب کنید:
npm install @nestjs/graphql graphql apollo-server-express @nestjs/jwt passport @nestjs/passport passport-jwt bcryptjs
مرحله 3: ماژول GraphQL را تنظیم کنید
-
ماژول GraphQL را پیکربندی کنید: باز کن
src/app.module.ts
و ماژول GraphQL را پیکربندی کنید:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { TypeOrmModule } from '@nestjs/typeorm';
import { join } from 'path';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
@Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'test',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
AuthModule,
UsersModule,
],
})
export class AppModule {}
مرحله 4: موجودیت کاربر را ایجاد کنید
- یک ساختار دایرکتوری ایجاد کنید:
mkdir -p src/users src/auth
-
موجودیت کاربر را ایجاد کنید: ايجاد كردن
src/users/user.entity.ts
:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { ObjectType, Field, ID } from '@nestjs/graphql';
@ObjectType()
@Entity()
export class User {
@Field(() => ID)
@PrimaryGeneratedColumn()
id: number;
@Field()
@Column()
username: string;
@Field()
@Column()
email: string;
@Column()
password: string;
}
مرحله 5: سرویس کاربر را ایجاد کنید
-
پیاده سازی منطق خدمات: باز کن
src/users/users.service.ts
و روش های خدمات را پیاده سازی کنید:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CreateUserInput } from './dto/create-user.input';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
async findOneByUsername(username: string): Promise<User | undefined> {
return this.usersRepository.findOne({ username });
}
async findOneByEmail(email: string): Promise<User | undefined> {
return this.usersRepository.findOne({ email });
}
async create(createUserInput: CreateUserInput): Promise<User> {
const hashedPassword = await bcrypt.hash(createUserInput.password, 10);
const user = this.usersRepository.create({ ...createUserInput, password: hashedPassword });
return this.usersRepository.save(user);
}
}
مرحله 6: User Resolver را ایجاد کنید
-
User Resolver را ایجاد کنید: ايجاد كردن
src/users/users.resolver.ts
:
import { Resolver, Mutation, Args } from '@nestjs/graphql';
import { UsersService } from './users.service';
import { User } from './user.entity';
import { CreateUserInput } from './dto/create-user.input';
@Resolver(of => User)
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
@Mutation(() => User)
async createUser(@Args('createUserInput') createUserInput: CreateUserInput): Promise<User> {
return this.usersService.create(createUserInput);
}
}
-
DTO را برای ورودی کاربر ایجاد کنید: ايجاد كردن
src/users/dto/create-user.input.ts
:
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class CreateUserInput {
@Field()
username: string;
@Field()
email: string;
@Field()
password: string;
}
مرحله 7: ماژول کاربر را ایجاد کنید
-
ماژول کاربر را ایجاد کنید: باز کن
src/users/users.module.ts
و آن را به روز کنید:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { UsersResolver } from './users.resolver';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UsersService, UsersResolver],
exports: [UsersService],
})
export class UsersModule {}
مرحله 8: احراز هویت را پیاده سازی کنید
-
سرویس Auth ایجاد کنید: ايجاد كردن
src/auth/auth.service.ts
:
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOneByUsername(username);
if (user && await bcrypt.compare(pass, user.password)) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
const payload = { username: user.username, sub: user.id };
return {
access_token: this.jwtService.sign(payload),
};
}
}
-
ماژول Auth را ایجاد کنید: باز کن
src/auth/auth.module.ts
و آن را پیکربندی کنید:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: 'secretKey', // Replace with your own secret
signOptions: { expiresIn: '60m' },
}),
],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
-
استراتژی JWT ایجاد کنید: ايجاد كردن
src/auth/jwt.strategy.ts
:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UsersService } from '../users/users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private usersService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'secretKey', // Replace with your own secret
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
مرحله 9: Auth Resolver را ایجاد کنید
-
Auth Resolver را ایجاد کنید: ايجاد كردن
src/auth/auth.resolver.ts
:
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { AuthService } from './auth.service';
import { AuthInput } from './dto/auth.input';
import { AuthResponse } from './dto/auth.response';
@Resolver()
export class AuthResolver {
constructor(private readonly authService: AuthService) {}
@Mutation(() => AuthResponse)
async login(@Args('authInput') authInput: AuthInput) {
const user = await this.authService.validateUser(authInput.username, authInput.password);
if (!user) {
throw new Error('Invalid credentials');
}
return this.authService.login(user);
}
}
-
DTO برای ورودی و پاسخ تأیید اعتبار ایجاد کنید: ايجاد كردن
src/auth/dto/auth.input.ts
:
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class AuthInput {
@Field()
username: string;
@Field()
password: string;
}
ايجاد كردن src/auth/dto/auth.response.ts
:
import { ObjectType, Field } from '@nestjs/graphql';
@ObjectType()
export class AuthResponse {
@Field()
access_token: string;
}
گام
10: از مسیرها با گارد احراز هویت محافظت کنید
-
GQL Auth Guard را ایجاد کنید: ايجاد كردن
src/auth/gql-auth.guard.ts
:
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
-
گارد را برای Resolver ها اعمال کنید: به روز رسانی
src/users/users.resolver.ts
برای محافظت از مسیرها:
import { UseGuards } from '@nestjs/common';
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { UsersService } from './users.service';
import { User } from './user.entity';
import { CreateUserInput } from './dto/create-user.input';
import { GqlAuthGuard } from '../auth/gql-auth.guard';
@Resolver(of => User)
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
@UseGuards(GqlAuthGuard)
@Query(() => [User])
async users(): Promise<User[]> {
return this.usersService.findAll();
}
@Mutation(() => User)
async createUser(@Args('createUserInput') createUserInput: CreateUserInput): Promise<User> {
return this.usersService.create(createUserInput);
}
}
مرحله 11: برنامه را اجرا کنید
- برنامه NestJS را راه اندازی کنید:
npm run start:dev
مرحله ۱۲: GraphQL API را تست کنید
-
به زمین بازی GraphQL دسترسی پیدا کنید: هدایت به
http://localhost:3000/graphql
برای دسترسی به زمین بازی GraphQL و آزمایش API خود با اجرای کوئری ها و جهش ها.
نمونه ای از جهش ها و کوئری های GraphQL
mutation {
createUser(createUserInput: { username: "john", email: "john@example.com", password: "password" }) {
id
username
email
}
}
mutation {
login(authInput: { username: "john", password: "password" }) {
access_token
}
}
- پرس و جو از همه کاربران (محافظت شده):
{
users {
id
username
email
}
}
این راهنما یک رویکرد اساسی برای اجرای احراز هویت و مجوز در یک NestJS GraphQL API ارائه می دهد. شما می توانید آن را بیشتر گسترش داده و بر اساس نیازهای برنامه خود سفارشی کنید.
سلب مسئولیت: این محتوا توسط هوش مصنوعی تولید شده است.