c# - ASP.NET Core Web API Facebook JWT 身份验证

标签 c# facebook asp.net-core jwt asp.net-core-webapi

我正在尝试在 asp.net 核心 Web Api 中实现基于 Facebook 的身份验证。我搜索了很多并阅读了大部分与使用 JWT 在 asp.net core 中进行身份验证相关的博客,但我没有找到任何使用 facebook 进行身份验证和生成 JWT 的文章。一些文章使用 ASP.NET Core MVC 来使用 facebook 登录。我尝试在 Web API 中添加它,但是在将用户名和密码提交到 facebook 而不是重定向到 ExternalLoginCallback 后,它给出了错误 404。

enter image description here

  [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);
    }

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        if (remoteError != null)
        {
            ErrorMessage = $"Error from external provider: {remoteError}";
            return BadRequest();
        }
        var info = await _signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return BadRequest();
        }
        var claims = info.Principal.Claims;
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("TokenKeys"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken("myapi",
          "myapi",
          claims,
          expires: DateTime.Now.AddDays(30),
          signingCredentials: creds);

        return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
    }

最佳答案

问题是我没有在 asp.net 管道中添加身份验证。在 Configure 方法中添加 app.UseAuthentication(); 后它起作用了。

之前

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {

                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

             app.UseMvc(routes =>
                {
                    routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");                 
                });        
}

之后

      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {

                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

                app.UseAuthentication();

             app.UseMvc(routes =>
                {
                    routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");                 
                });        
}

关于c# - ASP.NET Core Web API Facebook JWT 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786897/

相关文章:

c# .Net Core 2.1 授权属性 - 默认声明

c# - C#如何解析扩展方法调用?

c# - 返回满足特定条件的列表元素

c# - 创建一个单一的键绑定(bind),每次用任何数字按下控件时都会触发一个命令,然后将该数字作为参数传递?

facebook 页面插件无法正常工作

Facebook SDK 3.1 presentShareDialogModally 失败

c# - 具有多个定义的接口(interface) C#

ios - 如何使用 Swift 和 iOS 使用 Facebook 身份验证注销用户?

c# - 如何POST到rest api并使用c#中的非结束流?

c# - 渲染局部 View 时如何调用 Controller Action ?