2017-08-20 48 views
0

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

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) }); 
    } 
+0

后你有一个路由路径'/登入-facebook'为'ExternalLoginCallback'? –

+0

不,我没有,我应该在哪里配置路线? –

回答

0

问题是我没有在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?}");     
       });   
}