2

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) });
    }
4
  • Do you have a route that routes /signin-facebook to ExternalLoginCallback? Commented Aug 20, 2017 at 21:50
  • No , I don't have , Where should I configure that route ? Commented Aug 20, 2017 at 21:54
  • @BipnPaul Hi, I would to do the same way, Does this approach work fine? Commented May 23, 2018 at 10:22
  • @peymangilmour ,Yes,this approach is working. Commented May 24, 2018 at 15:42

1 Answer 1

1

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?}");                 
                });        
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.