【问题标题】:Cors Issue When IdentityServer redirect to redirect_uri当 IdentityServer 重定向到 redirect_uri 时出现 Cors 问题
【发布时间】:2020-12-04 20:41:47
【问题描述】:

我正在开发一个 SPA 网络应用程序,其中包括:

  • 在 https://localhost:5001 上运行的 API
  • IdentityServer4 在 https://localhost:5001 上运行
  • 一个移动应用程序,使用 API 的客户端,在 http://localhost:8100 上运行。它基于 ionic+capacitor 并使用 ionic serve 启动。

我无法从手机完成登录流程。现在起作用的是移动应用程序调用身份服务器进行授权,身份服务器验证用户,结果应该通过重定向返回给移动应用程序。我现在的问题是,当身份服务器尝试将呼叫重定向到移动应用程序时,我遇到了一个 cors 问题。

我的流程如下:

  • 移动应用程序使用代码流调用身份服务器授权端点。
  • 身份服务器将我重定向到交互式登录页面。
  • 我输入邮箱/密码并调用web api进行身份验证。
  • Identityserver 使用令牌和凭据调用 /authorize/callback
  • 授权/回调应该将我重定向到移动应用程序的redirect_uri (http://localhost:8100/authcallback),但是我得到如下 CORS 问题,问题的原因可能是什么?

登录 API 端点

       [HttpPost("login")] 
        public async Task<IActionResult> Login(UserResource model) { 
                   
            var result = await signInManager.PasswordSignInAsync(model.email, model.password, isPersistent: true, lockoutOnFailure: false);

            var context = await interaction.GetAuthorizationContextAsync(model.return_url);

            if (result.Succeeded) { 

                // @todo will need to be changed to support multiple organizations
                var uo = db.Users.Include(q => q.UserOrganization).Single( q => q.Email == model.email ).UserOrganization.First();
                uo.LastLogin = DateTime.UtcNow;
                await db.SaveChangesAsync();

                // let identity server know that we loggedin
                await identityEvents.RaiseAsync(new UserLoginSuccessEvent(
                     model.email, uo.UserId, model.email, clientId: context?.Client.ClientId
                ));


                return Redirect(model.return_url);
                /*return Ok( new{
                    email = model.email,
                    return_url = context.RedirectUri
                } );*/
            }

            // not including an empty object here raises an error, maybe a problem with core3-preview5
            await identityEvents.RaiseAsync(new UserLoginFailureEvent(model.email, "invalid credentials", clientId:context?.Client.ClientId));
            return NotFound(new {});

        }

【问题讨论】:

    标签: ionic-framework asp.net-identity identityserver4


    【解决方案1】:

    问题实际上是我从 XmlHttpRequest 发出重定向到不同的来源 (http://localhost:8100),所以 chrome 不会这样给我这个错误。

    修复是在登录控制器中返回 Ok() 而不是 Redirect(),在 javascript spa 客户端中,我使用 window.location 进行重定向。

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2020-11-04
      • 2021-03-15
      • 2022-01-12
      • 2020-09-09
      相关资源
      最近更新 更多