Nest.js : после авторизации защищенный роут остается недоступен. Почему?
В приложении, работающем под Nest.js и с авторизацией через passport-google-oauth20 после авторизации данные сохраняются в сессии, включая токен авторизации, но по защищенному роуту зайти не могу, происходит повторное перенаправление на страницу авторизации.
Пытался принудительно отправлять строку Authorization: Bearer <token> на запрос по защищенному роуту, но результата нет. Прошу совета, как решить проблему. Ниже - мой код.
GoogleStrategy:
import { Inject, Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-google-oauth20';
import { AuthService } from '../auth.service';
import { Request } from 'express';
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(
@Inject('AUTH_SERVICE') private readonly authService: AuthService,
) {
super({
clientID: '7820.apps.googleusercontent.com',
clientSecret: '3Ec',
callbackURL: 'http://localhost:3000/api/auth/google/redirect',
scope: ['email', 'profile'],
});
}
async validate(
accessToken: string,
refreshToken: string,
profile: Profile,
done: any,
request: Request & { accessToken?: string },
): Promise<any> {
const user = await this.authService.validateUser({
email: profile.emails[0].value,
});
if (user) {
user.accessToken = accessToken;
}
return user || null;
}
}
AuthController
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { GoogleAuthGuard } from './utils/Guards';
@Controller('auth')
export class AuthController {
constructor(private readonly configService: ConfigService) {}
@Get('google/login')
@UseGuards(GoogleAuthGuard)
handleLogin() {
return { msg: 'Google Authentication ' };
}
@Get('google/redirect')
@UseGuards(GoogleAuthGuard)
handleRedirect() {
return { msg: 'OK' }; // отрабатывает эта часть кода после первоначальной авторизации
}
UsersController
import {
Body, Controller, Delete, Get, Param, Patch, Post, Req, Res, UseFilters, UseGuards,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuthGuard } from '@nestjs/passport';
import { GoogleAuthGuard } from 'src/auth/utils/Guards';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersService } from './users.service';
import { DuplicateKeyExceptionFilter } from './utils/duplicateKeyExceptionFilter';
import UserDefaultValues from './utils/userDefaults';
@Controller('users')
export class UsersController {
constructor(
private readonly usersService: UsersService,
private readonly configService: ConfigService,
private readonly userDefaultValues: UserDefaultValues,
) {}
// http://localhost:3000/api/users/restricted
@Get('restricted') // не могу зайти на этот роут
@UseGuards(AuthGuard('google'))
restrictedRoute(): number {
return 123;
}
