【发布时间】:2021-06-19 06:57:43
【问题描述】:
我有一个 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();
});
}
}
}
【问题讨论】:
标签: c# asp.net-core .net-core jwt postman