Nestjs,无法验证jwt
Nestjs, can't verify jwt
我在前端发送请求,它 returns 401 Unathorized,当我在控制器上 console.log(headers) 时,没有守卫 x-access-token 存在,当我移除守卫时一切正常很好,图像 url 被发送回前端。
const response = await axios
.get(
'/auth/avatar',
{
headers: {
'x-access-token': sessionStorage.getItem('token')
},
params: {
username: sessionStorage.getItem('username')
}
}
)
console.log(response.data);
在 /auth 控制器上
@Get('/avatar')
@UseGuards(AuthGuard('jwt'))
getAvatar(
@Query('username') username: string,
): Promise<string> {
return this.authService.getAvatar(username);
}
服务:
getAvatar(username: string): Promise<string> {
return this.usersRepository.getAvatarUrl(username);
}
存储库:
async getAvatarUrl(username: string): Promise<string> {
const user = await this.findOne({ where: { username } });
return user.documentLocation;
}
jwt-策略
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private configService: ConfigService,
) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
授权模块:
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: 3600,
},
}),
}),
你打错了header。在您的示例中,您使用 auth headers:
获取
headers: {
'x-access-token': sessionStorage.getItem('token')
},
但在 jwt-stategy
中启用了不记名令牌 Authorization: Bearer ${token}
的身份验证。
您可以通过更新 jwt-strategy
来修复它:
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private configService: ConfigService,
) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromHeader('x-auth-token'),
});
}
async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
或:
await axios
.get(
'/auth/avatar',
{
headers: {
'Authorization': `Bearer ${sessionStorage.getItem('token')}`
},
params: {
username: sessionStorage.getItem('username')
}
}
)
我在前端发送请求,它 returns 401 Unathorized,当我在控制器上 console.log(headers) 时,没有守卫 x-access-token 存在,当我移除守卫时一切正常很好,图像 url 被发送回前端。
const response = await axios
.get(
'/auth/avatar',
{
headers: {
'x-access-token': sessionStorage.getItem('token')
},
params: {
username: sessionStorage.getItem('username')
}
}
)
console.log(response.data);
在 /auth 控制器上
@Get('/avatar')
@UseGuards(AuthGuard('jwt'))
getAvatar(
@Query('username') username: string,
): Promise<string> {
return this.authService.getAvatar(username);
}
服务:
getAvatar(username: string): Promise<string> {
return this.usersRepository.getAvatarUrl(username);
}
存储库:
async getAvatarUrl(username: string): Promise<string> {
const user = await this.findOne({ where: { username } });
return user.documentLocation;
}
jwt-策略
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private configService: ConfigService,
) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}
async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
授权模块:
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get('JWT_SECRET'),
signOptions: {
expiresIn: 3600,
},
}),
}),
你打错了header。在您的示例中,您使用 auth headers:
获取headers: {
'x-access-token': sessionStorage.getItem('token')
},
但在 jwt-stategy
中启用了不记名令牌 Authorization: Bearer ${token}
的身份验证。
您可以通过更新 jwt-strategy
来修复它:
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private configService: ConfigService,
) {
super({
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: ExtractJwt.fromHeader('x-auth-token'),
});
}
async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
或:
await axios
.get(
'/auth/avatar',
{
headers: {
'Authorization': `Bearer ${sessionStorage.getItem('token')}`
},
params: {
username: sessionStorage.getItem('username')
}
}
)