Startup.cs文件
using CRUD1.Config;
using CRUD1.Models;
using CRUD1.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
namespace CRUD1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Add your services here
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddScoped<IUserRespository,UserRespository>();
services.AddScoped<IUserService,UserService>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
});
services.AddDbContext<DemoContext>(options =>
options.UseMySql
(connectionString,ServerVersion.AutoDetect(connectionString))
);
// 生成 RSA 密钥对
RSA rsa = RSA.Create(2048);
var privateKey = rsa;
var publicKey = rsa.ExportRSAPublicKey();
// 将密钥保存到服务中,以便后续使用
services.AddSingleton(privateKey);
services.AddSingleton(publicKey);
// 配置 JWT 认证
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new RsaSecurityKey(privateKey)
};
});
//添加自定义接口访问权限 在接口上加[Authorize(Policy = "RequireTest1")]
services.AddAuthorization(options =>
{
options.AddPolicy("RequireTest1", policy =>
{
policy.RequireAuthenticatedUser(); // 用户必须经过身份验证
policy.RequireClaim(ClaimTypes.Name, "test1"); // 用户必须具有指定的声明(即 name 必须为 "test1")
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1");
});
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// 添加全局异常处理中间件
app.UseGlobalExceptionHandler();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//添加身份验证中间件
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}