ASP.NET核心Web API Facebook JWT认证
我正在尝试在asp.net核心Web API中实现基于Facebook的身份验证。 我搜索了很多,并阅读了大部分有关使用JWT在asp.net核心中进行身份验证的博客,但是我没有发现任何使用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管道中添加认证。 添加app.UseAuthentication();
在Configure
方法中工作。
之前
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?}");
});
}
链接地址: http://www.djcxy.com/p/22429.html