auth.controller.ts:
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '@nestjs/passport';
import { Request, Response } from 'express';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@UseGuards(AuthGuard('oauth2'))
async login() {
return 'hello world'
}
@Get('callback')
@UseGuards(AuthGuard('oauth2'))
callback(@Req() req:Request, @Res() res: Response) {
res.redirect('/');
}
}
策略.ts:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy,VerifyCallback } from 'passport-oauth2'
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy,'oauth2') {
constructor() {
super({
authorizationURL: 'www.example.com/login/connect/authorize',
tokenURL: 'www.example.com/login/connect/token',
clientID: 'client-id',
clientSecret: 'client-secret',
callbackURL: 'callback-url',
passReqToCallback: true
});
}
async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
var user = {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
};
console.log(user);
return done(null, user);
}
}
strategy.ts 未调用且未记录用户变量。
我尝试在nestjs中使用passport-oauth2包对用户进行身份验证。问题是,策略没有调用并且没有返回用户的accessToken。我的期望是strategy.ts文件应该返回accessToken和用户。
我不确定 UseGuards(AuthGuard('oauth2')) 是否有效。请问有什么解决办法吗!
在以下情况下,
validate
功能根本不会运行:
请求中未设置令牌
令牌无效
令牌已过期
令牌已加密,但未提供
secretOrKey
:
在您的示例中,创建令牌时的部分丢失,因此如果您使用密钥来加密令牌,则必须在
secretOrKey
类的构造函数中指定 LocalStrategy
属性并为其提供相同的属性创建令牌时用来加密令牌的字符串值
我也面临着同样的问题。你找到解决方案了吗?