c# - 如何使用 Postman 测试 jwt 身份验证
问题描述
我有一个 API,我为身份验证实现了 jwt,这是我的身份验证:
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
[HttpPost, Route("login")]
public IActionResult Login([FromBody]LoginModel user)
{
if (user == null)
{
return BadRequest("Invalid client request");
}
if (user.UserName == "test" && user.Password == "1234")
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sretKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokeOptions = new JwtSecurityToken(
issuer: "https://localhost:44361",
audience: "https://localhost:44378",
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(25),
signingCredentials: signinCredentials
);
在我的控制器中,我添加了授权属性,我在没有授权属性的情况下测试了我的控制器并且它有效,问题是为什么它未经授权使用凭据
这是我的启动
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.AddAuthentication(opt => {
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:44361",
ValidAudience = "https://localhost:44378",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sretKey@345"))
};
});
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.WithOrigins("http://localhost:44378")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddDbContext<DbContextClass>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
解决方案
将 AllowAnonymous 添加到您的登录操作
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody]LoginModel user)
{
.... your code
var token = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(token);
}
在此之后,您必须配置启动以使用此令牌。您还必须将此令牌添加到 Postman 以进行操作测试。Postman 有一个特殊的菜单 Autorization。打开它,选择令牌选项并将您的令牌粘贴到该字段中。如果需要,而不是登录并传递输入操作参数
并尝试像这样添加 app.UseAuthentication() :
app.UseAuthentication();
app.UseAuthorization();
推荐阅读
- javascript - 如果父级有类将类添加到其他 div
- business-process-management - IBM BPM 日期时间选择器
- html - 在 img 容器顶部显示 div
- r - 通过在 R 中添加零来塑造数据框
- wordpress - BuildFire WooCommerce 插件不起作用
- node.js - GraphQL 数据加载器与猫鼬填充
- c# - 使用数组属性绑定模型以在 ASP.NET Core MVC 中形成
- azure - 如何使用 Azure 逻辑应用操作在浏览器中下载文件
- c# - Visual Studio NUnit 适配器一次只能运行 10K 测试
- javascript - ENOENT:没有这样的文件或目录,取消链接