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