以下是一个使用ASP.NET Core 3.1实现基本和JWT授权及自定义策略的示例代码:
添加NuGet包: 在Visual Studio的解决方案资源管理器中右键单击项目 -> 选择“管理NuGet程序包” -> 在搜索框中搜索并安装以下NuGet包:
在Startup.cs文件的ConfigureServices方法中进行配置:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
public void ConfigureServices(IServiceCollection services)
{
// 配置JWT授权
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"))
};
});
// 配置授权策略
services.AddAuthorization(options =>
{
options.AddPolicy("CustomPolicy", policy =>
{
policy.RequireAuthenticatedUser(); // 需要用户已经通过验证
policy.RequireClaim("CustomClaimType", "CustomClaimValue"); // 需要包含自定义声明
});
});
services.AddControllers();
}
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
// 启用JWT授权中间件
app.UseAuthentication();
// ...
app.UseRouting();
// ...
// 启用授权中间件
app.UseAuthorization();
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize] // 使用基本授权
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
// 只有通过授权的用户才能访问该接口
return Ok("Authorized");
}
[Authorize(Policy = "CustomPolicy")] // 使用自定义授权策略
[HttpGet("custom")]
public IActionResult Custom()
{
// 只有满足自定义策略的用户才能访问该接口
return Ok("Custom Authorized");
}
}
以上代码示例了如何在ASP.NET Core 3.1中实现基本和JWT授权及自定义策略。你可以根据自己的需求进行相应的配置和调整。记得替换示例代码中的"your-issuer"、"your-audience"和"your-secret-key"为你实际使用的值。