您好,登錄后才能下訂單哦!
在C#中模擬Spring的RESTful安全控制,可以使用ASP.NET Core Web API和ASP.NET Core Identity系統(tǒng)來實現(xiàn)。以下是一個簡單的示例,展示了如何設(shè)置基本的身份驗證和授權(quán)。
首先,創(chuàng)建一個新的ASP.NET Core Web API項目。
dotnet new webapi -n SpringSecurityExample
cd SpringSecurityExample
你需要添加一些NuGet包來處理身份驗證和授權(quán)。
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Authorization
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
創(chuàng)建一個繼承自IdentityDbContext
的類來配置數(shù)據(jù)庫上下文。
// Data/ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace SpringSecurityExample.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
創(chuàng)建一個自定義的用戶類。
// Models/ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
namespace SpringSecurityExample.Models
{
public class ApplicationUser : IdentityUser
{
}
}
在Startup.cs
中配置服務(wù)。
// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SpringSecurityExample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllers();
services.AddAuthorization(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
services.AddScoped<IJwtTokenService, JwtTokenService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
創(chuàng)建一個服務(wù)來生成和驗證JWT令牌。
// Services/IJwtTokenService.cs
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace SpringSecurityExample.Services
{
public interface IJwtTokenService
{
string GenerateToken(ApplicationUser user);
bool ValidateToken(string token);
}
public class JwtTokenService : IJwtTokenService
{
private readonly string _jwtSecret;
private readonly IJwtEncoder _jwtEncoder;
public JwtTokenService(IConfiguration config, ILogger<JwtTokenService> logger)
{
_jwtSecret = config["JwtSecret"];
_jwtEncoder = new JwtSecurityTokenHandler().CreateEncoder();
}
public string GenerateToken(ApplicationUser user)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Name, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "SpringSecurityExample",
audience: "SpringSecurityExample",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: creds);
return _jwtEncoder.WriteToken(token);
}
public bool ValidateToken(string token)
{
try
{
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "SpringSecurityExample",
ValidateAudience = true,
ValidAudience = "SpringSecurityExample",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSecret)),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
var principal = new ClaimsPrincipal(new[] { new Claim(ClaimTypes.NameIdentifier, "123") });
var claimsIdentity = new ClaimsIdentity(principal.Claims, JwtBearerDefaults.AuthenticationScheme);
var tokenHandler = new JwtSecurityTokenHandler();
var result = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
return result.IsValid;
}
catch (Exception ex)
{
logger.LogError(ex, "Invalid JWT token");
return false;
}
}
}
}
創(chuàng)建一個控制器來處理API請求,并使用授權(quán)屬性來保護端點。
// Controllers/ValuesController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace SpringSecurityExample.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
private readonly IJwtTokenService _jwtTokenService;
public ValuesController(IJwtTokenService jwtTokenService)
{
_jwtTokenService = jwtTokenService;
}
[HttpGet("{id}")]
[Authorize]
public async Task<IActionResult> Get(int id)
{
return Ok($"Value for ID: {id}");
}
[HttpPost]
[Authorize]
public async Task<IActionResult> Post([FromBody] string value)
{
return CreatedAtAction(nameof(Get), new { id = 1 }, value);
}
}
}
在appsettings.json
中配置數(shù)據(jù)庫連接字符串。
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=SpringSecurityExampleDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"JwtSecret": "your_jwt_secret"
}
運行應(yīng)用程序并測試API端點。
dotnet run
你可以使用Postman或其他工具來測試API端點。首先,登錄以獲取JWT令牌,然后在后續(xù)請求中使用該令牌進行身份驗證和授權(quán)。
以上示例展示了如何在C#中模擬Spring的RESTful安全控制。通過使用ASP.NET Core Web API和ASP.NET Core Identity系統(tǒng),你可以輕松地實現(xiàn)身份驗證和授權(quán)功能。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。