ASP.NET Core JWT 认证 API 使用教程
项目目录结构及介绍
aspnet-core-jwt-authentication-api/
├── Controllers/
│ └── UsersController.cs
├── Entities/
│ └── User.cs
├── Helpers/
│ ├── AppSettings.cs
│ ├── AutoMapperProfile.cs
│ ├── JwtUtils.cs
│ └── SwaggerOptions.cs
├── Models/
│ ├── AuthenticateRequest.cs
│ ├── AuthenticateResponse.cs
│ ├── RegisterRequest.cs
│ └── UpdateRequest.cs
├── Services/
│ └── UserService.cs
├── _middleware/
│ └── JwtMiddleware.cs
├── appsettings.Development.json
├── appsettings.json
├── Program.cs
├── Startup.cs
└── aspnet-core-jwt-authentication-api.csproj
目录结构说明
- Controllers/: 包含 API 控制器,负责处理 HTTP 请求。
- Entities/: 包含实体类,如
User
类。 - Helpers/: 包含辅助类,如配置、JWT 工具、AutoMapper 配置等。
- Models/: 包含请求和响应模型。
- Services/: 包含业务逻辑服务,如
UserService
。 - _middleware/: 包含自定义中间件,如 JWT 中间件。
- appsettings.json: 配置文件,包含应用设置和 JWT 密钥。
- Program.cs: 项目的启动文件。
- Startup.cs: 配置服务和应用中间件。
- aspnet-core-jwt-authentication-api.csproj: 项目文件。
项目的启动文件介绍
Program.cs
var builder = WebApplication.CreateBuilder(args);
// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// 配置 HTTP 请求管道
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
启动文件说明
- Program.cs: 这是项目的入口点,负责配置和启动应用。它使用
WebApplication.CreateBuilder
创建应用实例,并配置服务和中间件。
项目的配置文件介绍
appsettings.json
{
"AppSettings": {
"Secret": "THIS IS USED TO SIGN AND VERIFY JWT TOKENS, REPLACE IT WITH YOUR OWN SECRET, IT CAN BE ANY STRING"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
配置文件说明
- appsettings.json: 包含应用的配置设置,如 JWT 密钥、日志级别和允许的主机。
- AppSettings:Secret: 用于签名和验证 JWT 令牌的密钥。
- Logging: 配置日志级别。
- AllowedHosts: 配置允许访问的主机。
通过以上内容,您可以了解如何使用和配置 aspnet-core-jwt-authentication-api
项目。希望这份教程对您有所帮助!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考