• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

[세션30] fetchUser시 UseGuard 401에러

23.07.17 17:01 작성 조회수 180

0

안녕하세요,

jwt토큰을 입력하여 사용자 인가를 받고 싶은데 그 과정에서 계속 오류가 나서 문의드립니다. 제가 확인하기로는 코드도 정확히 입력하고, HTTP HEADERS로 보내주는 토큰도 문제 없어서요.

에러 강의에서 jwt를 넣어주지 않았을 때 발생한다는 에러가 발생합니다.

제가 보기에는 토큰값이 잘못된것 같은데, login으로 받아온 토큰을 바로 넣는거라 만료가 되지도 않았을텐데 해결이 안되네요.

제 코드는 아래와 같습니다.

users.resolver.ts

// users.resolver.ts

import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { User } from './entities/user.entity';
import { UsersService } from './users.service';
import * as bcrypt from 'bcrypt';
import { UseGuards } from '@nestjs/common';
import { GqlAuthAccessGuard } from '../auth/guards/gql-auth.guard';
// import { AuthGuard } from '@nestjs/passport';
// 추가

@Resolver()
export class UsersResolver {
  constructor(
    private readonly usersService: UsersService, //
  ) {}

  @UseGuards(GqlAuthAccessGuard) // 수정
  @Query(() => String)
  fetchUser(): string {
    console.log('인가에 성공하였습니다');
    return '인가에 성공하였습니다.';
  }

  @Mutation(() => User)
  async createUser(
    @Args('email') email: string,
    @Args('password') password: string,
    @Args('name') name: string,
    @Args({ name: 'age', type: () => Int }) age: number,
  ): Promise<User> {
    //   const hashedPassword = await bcrypt.hash(password, 10);
    //   return this.usersService.create({ email, hashedPassword, name, age });
    // }
    return this.usersService.create({ email, password, name, age });
  }
}

 

gql-auth.guard.ts


import { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';

export class GqlAuthAccessGuard extends AuthGuard('access') {
  getRequest(context: ExecutionContext) {
    const gqlContext = GqlExecutionContext.create(context);
    return gqlContext.getContext().req;
  }
}

 

jwt-access.strategy.ts


import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: '나의비밀번호',
    });
  }

  validate(payload) {
    console.log('페이로드', payload);

    return {
      id: payload.sub, 
    };
  }
}

 

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthResolver } from './auth.resolver';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { JwtAccessStrategy } from './strategy/jwt-access.strategy';

@Module({
  imports: [
    JwtModule.register({}),
    UsersModule, // 서비스를 각각 불러오기보다는 module을 통으로 불러오는게 낫다. 원래는 import 에 TypeOrmModule.forFeature([Users])& providers에 UsersServie가 있었음.
  ],

  providers: [
    JwtAccessStrategy,
    AuthResolver, //
    AuthService, //
  ],
})
export class AuthModule {}

답변 1

답변을 작성해보세요.

0

안녕하세요! yskim님!

코드는 잘 작성해 주신 것 같아요!

해당 에러는 일반적으로 토큰이 만료되었거나 비밀번호가 틀렸거나 할 때 나오는 메시지예요!

따라서, 나의비밀번호가 잘 작성되어 있는지, 수업때 리프레시 토큰 수업을 진행하기 위해 시로 토큰 만료시간을 10초로 변경했었는데 이때문에 너무 빨리 만료된 것은 아닌지, 로그인 api를 한번 확인해 보아야 할 것 같아요!