ASP.NET Core身份验证和Web API安全可以通过以下步骤进行解决:
Startup.cs
文件的ConfigureServices
方法中添加身份验证和授权服务:public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
};
});
// 添加授权服务
services.AddAuthorization();
services.AddControllers();
}
Startup.cs
文件的Configure
方法中添加身份验证中间件:public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 省略其他代码
app.UseAuthentication();
app.UseAuthorization();
// 省略其他代码
}
[Authorize]
特性:[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult Get()
{
// 身份验证成功,可以返回数据
return Ok("Authenticated!");
}
}
TokenService
类:public class TokenService
{
private readonly IConfiguration _config;
public TokenService(IConfiguration config)
{
_config = config;
}
public string GenerateToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config["Jwt:SecretKey"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "username")
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
TokenService
服务,并在控制器的登录方法中生成JWT令牌:[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly TokenService _tokenService;
public AuthController(TokenService tokenService)
{
_tokenService = tokenService;
}
[HttpPost("login")]
public IActionResult Login()
{
var token = _tokenService.GenerateToken();
return Ok(new { token });
}
}
这样,当调用需要身份验证的API方法时,客户端需要在请求的Authorization
头中添加Bearer
,其中
是通过登录API方法生成的JWT令牌。