2
votes

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.

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) });
    }
1
Do you have a route that routes /signin-facebook to ExternalLoginCallback?Jeroen Vannevel
No , I don't have , Where should I configure that route ?Bipn Paul
@BipnPaul Hi, I would to do the same way, Does this approach work fine?peyman gilmour
@peymangilmour ,Yes,this approach is working.Bipn Paul

1 Answers

1
votes

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