尝试通过Auth0
登录进行身份验证时,前端出现错误。我的后端应该能够使用社交提供程序(即Auth0
或Google
)授权用户,并使用JSON Web Tokens
(JWTs
)对他们进行身份验证。
我使用passportJS
创建了所有后端,并添加了Auth0
护照策略以及Google策略。在测试两种策略的端点时,都可以与Postman
配合使用。
但是随后出现了前端部分,在这里我对localhost:3000/auth/auth0
进行了API调用,并且发生了以下错误:
Access to XMLHttpRequest at 'https://mydomain.auth0.com/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fauth0%2Fcallback&scope=openid%20profile&state=7cQWAAvioTLCniVqAy4ghHXK&client_id=cDB1F0gO9QWyNqHh1TGuVl7It5nYQrs9' (redirected from 'http://localhost:3000/auth/auth0') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
后端代码:
文件main.ts
async function bootstrap() {
// Nest App
const app = await NestFactory.create(ApplicationModule, { cors: true });
// Body parser middleware with increase limits
app.use(bodyParser.urlencoded({limit: '5mb', extended: true}));
app.use(bodyParser.json({limit: '5mb'}));
app.enableCors();
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
const port: number = +process.env.PORT || 3000;
await app.listen(port, () => {
// tslint:disable-next-line:no-console
console.log(`Nest app is listening on port ${port}.`);
});
}
bootstrap();
文件auth0.strategy.ts
@Injectable()
export class Auth0Strategy extends PassportStrategy(Strategy, 'auth0')
{
constructor(private readonly authService: AuthService) {
super({
domain: config.auth0.domain,
clientID: config.auth0.clientID,
clientSecret: config.auth0.clientSecret,
callbackURL: 'http://localhost:3000/auth/auth0/callback',
passReqToCallback: true,
audience: config.auth0.audience,
scope: 'openid profile',
})
}
async validate(_request: any, _accessToken: string, _refreshToken: string, profile: any, done: Function) {
try {
const jwt: string = await this.authService.validateOAuthLogin(profile.id, Provider.AUTH0);
const user = { jwt };
done(null, user);
}
catch (err) {
done(err, false);
}
}
}
文件auth.controller.ts
@Get('auth0')
@UseGuards(AuthGuard('auth0'))
auth0Login() {
// initiates the Auth0 OAuth2 login flow
}
@Get('auth0/callback')
@UseGuards(AuthGuard('auth0'))
async auth0Callback(@Req() req, @Res() res) {
const jwt: string = req.user.jwt;
if (jwt) {
res.redirect('http://localhost:4200/login/succes/' + jwt);
} else {
res.redirect('http://localhost:4200/login/failure');
}
}
前端代码:
文件authentication.service.ts
public login(): void {
this.apiService.get('auth/auth0').subscribe(
(res) => {
console.log('result', res);
}, (err) => {
console.log('error', err);
});
}
我希望弹出Auth0
登录页面,因此必须将用户重定向到该登录页面,但是由于CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
不会发生任何事情