C# .NET CORE 2.1 JWT承载授权未在请求时调用-始终返回200 OK

C# .NET CORE 2.1 JWT承载授权未在请求时调用-始终返回200 OK,c#,jwt,C#,Jwt,我正在做一个项目,我有一个单独的前端和后端,我想用JWT承载令牌保护我的后端API 当我从postman发送一个get请求而没有附加任何令牌时,API总是返回200OK。调试控制台确认未调用授权中间件。但是我确实收到了一个HTTPS错误?? 下面是我的控制台图片的链接(新用户不能在问题中直接使用图片) 我已经看了这个简单的例子来说明我到底需要什么。他的工作没有问题,他的应用程序的控制台显示授权被调用,我得到401未经授权。当我使用他的方法时,什么都没有发生,我总是得到200好 在startup

我正在做一个项目,我有一个单独的前端和后端,我想用JWT承载令牌保护我的后端API

当我从postman发送一个get请求而没有附加任何令牌时,API总是返回200OK。调试控制台确认未调用授权中间件。但是我确实收到了一个HTTPS错误?? 下面是我的控制台图片的链接(新用户不能在问题中直接使用图片)

我已经看了这个简单的例子来说明我到底需要什么。他的工作没有问题,他的应用程序的控制台显示授权被调用,我得到401未经授权。当我使用他的方法时,什么都没有发生,我总是得到200好

在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();
    }
}
名称空间API
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddCors();
services.AddMvc();
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(选项=>
{
options.RequireHttpsMetadata=false;
options.SaveToken=true;
options.TokenValidationParameters=新的TokenValidationParameters
{
validateisuer=true,
ValidateAudience=false,
ValidateLifetime=true,
ValidateSuersigningKey=true,
ValidIssuer=配置[“Jwt:Issuer”],
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“Jwt:Key”]))
};
});
var connection=Environment.GetEnvironmentVariable(“DB”);
services.AddDbContext(options=>options.UseSqlServer(connection));
services.addScope();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
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();
    }
[授权]
[ApiController]
[Microsoft.AspNetCore.Mvc.Route(“api/[controller]”)
公共类公司控制器:ControllerBase
{
私人爱道道;
上市公司控制人(IDAO db)
{
dao=db;
}
[Microsoft.AspNetCore.Mvc.HttpGet(“搜索/{keyword}”)]
public ActionResult SearchCompanys(字符串关键字)
{
返回JsonConvert.SerializeObject(dao.SearchCompanys(关键字));
}
//获取api/company/basic/5
[Microsoft.AspNetCore.Mvc.HttpGet(“basic/{id}”)]
公共操作结果GetBasic(字符串id)
{
返回dao.GetCompanyByRegNrBasic(id.ToString();
}

您似乎忘记添加授权

就像@ste-fu所说的,试着在服务下面添加这个


使用Mvc Core 2.2而不是使用
services.AddAuthorization();
do
services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().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"]))
                };
            });

试试这个对我有用。

中间件的顺序很重要-尝试在配置的前面添加身份验证尝试了这个,但luckI没有发现任何错误(错误)解决方案。我创建了一个新项目,并将所有内容从旧项目复制到新项目。授权现在起作用了!我不知道出了什么问题,可能是我的一些导入错误或其他什么…?我尝试了这个,但不起作用。我还尝试放置AddAuthentication(…)在顶部添加授权-也没有success@Alexander我确实喜欢Avrohom的建议,它对我很有效。首先是AddAuthorization(),然后是AddAuthentication()。也不要忘记调用app.UseAuthentication();在配置中。尝试简要解释一下您的解决方案提供了什么Hanks mate,您救了我一天!您能否详细说明所提到的方法和您提供的答案有何不同?
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"]))
                };
            });