如何在Nest.js的Passport Local策略中获取请求头?
How to Access Request Headers in Passport Local Strategy's Validate Method
Got it, let's sort this out for you! The key here is to tell Passport to pass the full request object to your validate callback—right now, it's only passing the username/email and password. Here's exactly how to adjust your code:
First, update your strategy's constructor to enable the passReqToCallback option. This will make the request object the first parameter in your validate method, letting you grab headers directly from it.
Here's the modified code with comments explaining the changes:
import { Request } from 'express'; // Don't forget to import Request from express @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super({ usernameField: 'email', passReqToCallback: true // Enable this to pass the full request to validate }) } // Add req as the first parameter now async validate(req: Request, email: string, password: string): Promise<IUser> { // Extract subdomain from request headers const host = req.headers.host; if (!host) { throw new UnauthorizedException('Host header is missing'); } const subdomain = host.split(".")[0]; // Pass subdomain to your auth service const user = await this.authService.validateUser({ email, password, subdomain }); if (!user) { throw new UnauthorizedException(); } return user; } }
Quick Breakdown:
passReqToCallback: true: This flag tells Passport to inject the entireRequestobject as the first argument to yourvalidatemethod. Without this, you can't access headers, request params, or any other request-specific data.req.headers.host: Thehostheader holds the full domain string (e.g.,subdomain.your-app.com). Splitting it by "." gives you the subdomain as the first element of the resulting array.- Missing host check: Added a quick guard clause to handle cases where the
hostheader might be missing, preventing unexpected runtime errors.
This setup will let you extract the subdomain and pass it to your authService.validateUser method exactly as you wanted!
内容的提问来源于stack exchange,提问作者Daniel Levy
相关产品推荐
相关产品推荐

