【发布时间】:2019-03-15 10:52:04
【问题描述】:
我正在做一个项目,我有一个单独的前端和后端,我想用 JWT 不记名令牌保护我的后端 API。
当我从邮递员发送一个未附加任何令牌的获取请求时,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();
}
【问题讨论】:
-
中间件的顺序很重要 - 尝试在配置的前面添加身份验证
-
尝试了这个没有任何运气
-
我找到了一个(坏的)解决方案。我创建了一个新项目,并将旧项目中的所有内容复制到新项目中。授权立即生效!我不知道出了什么问题,也许我的一些导入错误或什么......?