代码之家  ›  专栏  ›  技术社区  ›  johnny 5

.NET核心内置授权代码流

  •  0
  • johnny 5  · 技术社区  · 7 年前

    我正在努力简化我的应用程序的登录过程。抢先使用IdentityServer登录,但我不需要整个令牌服务器,所以我现在正在降级过程中,只使用ASP.NET标识。

    在此之前,我可以通过以下方式通过第三方登录:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        // Request a redirect to the external login provider.
        var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }
    

    这允许我与第三方(如CoinBase)登录,但我对这项工作的工作方式感到困惑,因为我看不到他们收到授权代码的地方。

    我已经从OAuth提供者那里获得了一个授权代码,现在我需要获得访问令牌。我可以很容易地通过手动提出请求,例如

    POST /oauth/token HTTP/1.1
    Host: authorization-server.com
    
    grant_type=authorization_code
    &code=xxxxxxxxxxx
    &redirect_uri=https://example-app.com/redirect
    &client_id=xxxxxxxxxx
    &client_secret=xxxxxxxxxx
    

    但是我觉得.NET中有一些内置的功能可以执行这个请求并将令牌存储在用户管理器中。有人知道一个内置的方法吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Alexander Higgins    7 年前

    我建议使用Identity Server Nuget包进行客户端身份验证,即使您不需要服务器。

    它提供了您在引擎盖下所指的处理各种誓言流的功能,因此您不必自己实现它们。

    否则,您将不得不在客户机、服务器端应用程序和正在进行身份验证的服务之间手动请求。这可以得到 quite complex 取决于你的需要。

    使用nuget包,您可以使用openid connect连接外部认证提供者,无论是coinbase还是其他一些服务,只需通过依赖注入几行代码。

    从那里你可以 handle the callback and sign the user in .

    有关更多信息,请查看 Sign-in with External Identity Providers Adding Support for External Authentication 官方身份服务器文档中的页面。

    默认情况下,ASP.NET标识将在本地端点“/account/externallogin”下处理回调。如果需要自定义功能, you can scaffold that page 从基础RCL定制它。

        2
  •  0
  •   johnny 5    7 年前

    结果我想的太多了。我可以使用在Identity Server中配置的相同OAuth提供程序,并将它们移植到我的.NET核心项目中,然后使用相同的登录方法

    [HttpPost]
    [AllowAnonymous]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        // Request a redirect to the external login provider.
        var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }
    

    要挑战我在Angular中唯一需要做的就是提供一个表单,它将调用我的外部登录方法:

    <form #form method="post" class="form-horizontal" action="https://localhost:44370/Account/ExternalLogin">
        <div>
            <p>
                <button ion-button block [disabled]="isDisabled" (click)="form.submit()" type="submit" title="Log in using your Coinbase account">
                    Coinbase
                </button>
                <input type="hidden" name="provider" value="Coinbase">
            </p>
        </div>
    </form>