Cors 阻止不和谐 oauth2 登录

Posted

技术标签:

【中文标题】Cors 阻止不和谐 oauth2 登录【英文标题】:Cors blocks discord oauth2 login 【发布时间】:2021-01-10 11:00:05 【问题描述】:

我正在尝试使用不和谐功能进行注册。流程如下所示:

Auth flow of my application

下一个前端还不存在,所以我用一个基本的 html 文件来测试它:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="onClick()">Login with discord</button>
    <script>
      const onClick = async () => 
        const res = await fetch('https://api.league.pr1sm.gg/auth/discord', 
          method: 'GET',
          redirect: 'follow',
          headers: 
            'Access-Control-Allow-Origin': 'https://api.league.pr1sm.gg',
          ,
        );
        console.log('onClick -> res->text', await res.text());
        console.log('onClick -> res', await res);
      ;
    </script>
  </body>
</html>

The backend code is located here

html部署在https://league.pr1sm.gg,后端部署在https://api.league.pr1sm.gg

这是我收到的错误:

Access to fetch at 'https://api.league.pr1sm.gg/auth/discord' from origin 'https://league.pr1sm.gg' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Request:A

Request:B

【问题讨论】:

【参考方案1】:

您需要在应用程序中启用跨域资源共享才能通过。您可能还需要告诉 discord 哪些回调 url 允许进入您的应用程序。

要启用 CORS,请转到 ma​​in.ts 并添加此...

app.enableCors();

更多信息,请查看官方文档。

https://docs.nestjs.com/techniques/security#cors

【讨论】:

我已经这样做了。就像你写的那样 app.enableCors( origin: 'league.pr1sm.gg', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', preflightContinue: true, optionsSuccessStatus: 200, credentials: true, );

以上是关于Cors 阻止不和谐 oauth2 登录的主要内容,如果未能解决你的问题,请参考以下文章

Blazor oauth2 被 CORS 阻止

如何实际使用使用不和谐 oauth2 请求的数据

如何获取不和谐 oauth2 隐式授权的范围值?

GitHub页面的不和谐Oauth2?

Spring Oauth2 CORS

Spring security 4.2.3,OAUTH 2,/oauth/token 端点,CORS 不工作