[英].NET CORE 2.1 JWT Bearer Authorization not invoked on request - Always returns 200 OK
I am doing a project where i have a separate front- and backend, and i want to protect my backend API with JWT bearer tokens. 我正在做一个有独立的前端和后端的项目,我想用JWT承载令牌保护后端API。
When i send a get request from postman without any tokens attached, the API always return 200 OK. 当我从邮递员发送不带任何令牌的get请求时,API始终返回200 OK。 The debug console confirms that the Authorization middleware was not invoked. 调试控制台确认未调用授权中间件。 I do however get a HTTPS error?? 但是,我确实收到HTTPS错误吗? Below is a link to an image of my console (new users can't have pictures directly in a question). 以下是控制台图像的链接(新用户不能直接在问题中拥有图片)。
I've looked at this guy's simple example of what i need exactly. 我看过这个家伙的简单例子,说明我确实需要什么。 His works no problem, and the console of his app shows authorization getting invoked, and i get 401 Unauthorized. 他的作品没问题,他的应用程序控制台显示授权被调用,我得到401 Unauthorized。 When i use his approach nothing happens and i always get 200 OK. 当我使用他的方法时,什么也没发生,我总是得到200 OK。
In startup.cs i have both tried using services.AddMvc() as seen below, but also services.AddMvcCore().AddAuthorization(). 在startup.cs中,我都尝试过使用services.AddMvc(),如下所示,还尝试了services.AddMvcCore()。AddAuthorization()。 Both resulted in Authorization not being invoked 两者都导致未调用授权
Here is my startup.cs: 这是我的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();
}
}
} }
Here is a controller: 这是一个控制器:
[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();
}
With Mvc Core 2.2 instead of using services.AddAuthorization();
使用Mvc Core 2.2而不是使用services.AddAuthorization();
do services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
做services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization();
all in one chained line. 全部在一条链上。
It looks like you forgot to add the authorization. 您好像忘记了添加授权。
Like @ste-fu said, try add this below the services.AddAuthentication(..); 就像@ ste-fu所说的那样,尝试将其添加到services.AddAuthentication(..)之下;
services.AddAuthorization();
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"]))
};
});
Try this its working for me. 试试这个对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.