首先,您需要创建一个ASP.NET Core Web应用程序。可以使用Visual Studio或使用命令行工具创建项目。
dotnet new webapi -n AuthExample
cd AuthExample
dotnet add package Microsoft.AspNetCore.Authentication
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(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-secret-key"))
};
});
// 添加其他服务配置
}
请替换your-issuer
,your-audience
和your-secret-key
为您自己的值。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 添加其他中间件配置
app.UseAuthentication();
app.UseAuthorization();
// 添加其他中间件配置
}
AuthController.cs
,并添加以下代码:using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult Get()
{
return Ok("Authenticated");
}
}
该控制器包含一个GET方法,[Authorize]
特性确保只有经过身份验证的用户才能访问该方法。
dotnet run
现在,您可以使用任何HTTP客户端(如Postman或浏览器)来访问https://localhost:5001/api/auth
,并且只有在提供有效的身份验证令牌时才能成功访问。
请注意,上述代码示例中的身份验证仅使用了基本的JWT身份验证配置。您可能需要进一步自定义和配置身份验证以满足您的需求。