我正在做一个有独立的前端和后端的项目,我想用JWT承载令牌保护后端API。
当我从邮递员发送不带任何令牌的get请求时,API始终返回200 OK。调试控制台确认未调用授权中间件。但是,我确实收到HTTPS错误吗? 以下是控制台图像的链接(新用户不能直接在问题中拥有图片)。
我看过这个guy's我需要的简单示例。他的作品没问题,他的应用程序控制台显示授权被调用,我得到401 Unauthorized。当我使用他的方法时,什么也没发生,我总是得到200 OK。
在startup.cs中,我都尝试过使用services.AddMvc(),如下所示,还尝试了services.AddMvcCore()。AddAuthorization()。两者都导致未调用授权
这是我的startup.cs:
namespace API
{
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.AddCors();
services.AddMvc();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
var connection = Environment.GetEnvironmentVariable("DB");
services.AddDbContext<CoPassContext>(options => options.UseSqlServer(connection));
services.AddScoped<IRepository, Repository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(c => c
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());
app.UseAuthentication();
app.UseMvc();
}
}
}
这里是控制器:
[Authorize]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
public class CompanyController : ControllerBase
{
private IDAO dao;
public CompanyController(IDAO db)
{
dao = db;
}
[Microsoft.AspNetCore.Mvc.HttpGet("search/{keyword}")]
public ActionResult<string> SearchCompanies(string keyword)
{
return JsonConvert.SerializeObject(dao.SearchCompanies(keyword));
}
// GET api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet("basic/{id}")]
public ActionResult<string> GetBasic(string id)
{
return dao.GetCompanyByRegNrBasic(id).ToString();
}
答案 0 :(得分:0)
您似乎忘记了添加授权。
就像@ ste-fu说的那样,尝试将其添加到services.AddAuthentication(..);
services.AddAuthorization();
答案 1 :(得分:0)
使用Mvc Core 2.2而不是使用services.AddAuthorization();
,只需在一条链中完成services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
。
答案 2 :(得分:0)
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
尝试一下对我有用。