ASP.NET Core Web API Facebook JWT Authentication

I am trying to implement Facebook based authentication in asp.net core Web Api. I searched a lot and read most of the blog related to the authentication in asp.net core using JWT but I did not found any of that article which is using facebook to authenticate and generate JWT. Some of the article were using ASP.NET Core MVC to login using facebook.I tried adding that in web API but After submitting username and password to facebook instead of redirecting to ExternalLoginCallback it gives error 404.

在这里输入图像描述

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

The problem was that I was not adding authentication in asp.net pipeline. After adding app.UseAuthentication(); in Configure Method it worked.

Before

     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?}");                 
                });        
}

After

      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?}");                 
                });        
}
链接地址: http://www.djcxy.com/p/22430.html

上一篇: Asp.net核心身份和基于令牌的认证

下一篇: ASP.NET核心Web API Facebook JWT认证