我有一个 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();
});
}
}
}
答案 0 :(得分:1)
在您的登录操作中添加 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();