使用ASP.NET Core API进行身份验证时,可以结合JWT(JSON Web Tokens)进行身份验证,而不会破坏网站的内置身份验证。下面是一个使用ASP.NET Core API和JWT进行身份验证的代码示例:
首先,需要安装以下NuGet包:
然后,在Startup.cs文件中进行如下配置:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-signing-key"))
};
});
// ...
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
// 启用身份验证中间件
app.UseAuthentication();
// ...
app.UseRouting();
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
// ...
}
然后,在控制器中,可以使用[Authorize]
特性来标记需要身份验证的路由。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
// ...
[HttpGet]
public IActionResult Get()
{
// 在这里处理需要身份验证的逻辑
return Ok("Authenticated user data");
}
// ...
}
当客户端发送请求时,需要在请求的头部中包含有效的JWT。例如,可以使用HttpClient
发送包含JWT的请求:
using System.Net.Http;
using System.Net.Http.Headers;
private async Task GetApiData()
{
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your-jwt-token");
HttpResponseMessage response = await client.GetAsync("https://your-api-url/api/users");
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
return data;
}
return string.Empty;
}
以上代码示例演示了如何在ASP.NET Core API中使用JWT进行身份验证,而不会破坏网站的内置身份验证。你可以根据自己的需求进行相应的修改和扩展。