首页 > 解决方案 > 使用 Giraffe 登录 Facebook

问题描述

我正在尝试将我的 MVC 应用程序转换为 Giraffe,但有一个最终老板:Facebook 登录。

除了挑战之外,我已经能够让每个部分都正常工作:

        public IActionResult ExternalLogin(string returnUrl = null)
        {
            var properties = _signInManager.ConfigureExternalAuthenticationProperties("Facebook", $"/mycallbackurl?returnUrl={returnUrl}");
            return new ChallengeResult("Facebook",   properties);
        }

我如何在 Giraffe 中做到这一点?

当我简单地返回challenge "Facebook"流程时工作正常,除非我回到我的回调端点

let! info = signInManager.GetExternalLoginInfoAsync() 信息为空。

控制台甚至说

info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
      AuthenticationScheme: Identity.External signed in

如何获取此事件以使用 登录我的用户signInManager.SignInAsync

启动.cs


 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                    {
                        o.Cookie.Expiration = TimeSpan.FromDays(16);
                        o.Cookie.Name = "_myt";
                        o.SlidingExpiration = true;
                    }

                )
                .AddFacebook(o =>
                {
                    o.AppId = Configuration["Authentication:Facebook:AppId"];
                    o.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                });

标签: .netasp.net-coref#asp.net-authenticationf#-giraffe

解决方案


signInManager.GetExternalLoginInfoAsync()依赖于包含回调 url 的挑战,而 Giraffe 的挑战没有这样做。

一个解决方案是推出自己的challenge

let externalLogin : HttpHandler =
    fun (next : HttpFunc) (ctx : HttpContext) ->
        task {
            let provider = "Facebook"

            let returnUrl =
                (ctx.TryGetQueryStringValue "returnUrl"
                 |> Option.map (sprintf "?returnurl=%s")
                 |> Option.defaultValue "")

            let items = // This must be a mutable dictionary to work
                System.Collections.Generic.Dictionary<string, string>()
            
            items.Add("LoginProvider", provider)
                
            let props = AuthenticationProperties(items, RedirectUri = (sprintf "/myCallbackEndpointWhereILogTheUserIn%s" returnUrl))
            
            do! ctx.ChallengeAsync(provider, props)
            return! next ctx
        }

推荐阅读