简体   繁体   English

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

[英].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). 以下是控制台图像的链接(新用户不能直接在问题中拥有图片)。

My console 我的控制台

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.

相关问题 Swashbuckle .NET Core 2 中 JWT 承载的授权 - Authorization for JWT bearer in Swashbuckle .NET Core 2 .NET Core 授权 - JWT 承载上的常量 403 - .NET Core Authorization - Constant 403 on JWT Bearer .Net Core 2.1 CORS和Firebase JWT授权 - .Net Core 2.1 CORS and Authorization with Firebase JWT Asp.Net Identity:Web Api请求授权失败,返回200 OK - Asp.Net Identity: Web Api request fails authorization, returns 200 OK 在 ASP.NET Core 中的 Swagger 中使用 JWT(授权:承载) - Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core JWT不记名令牌授权不起作用asp net core web api - JWT bearer token Authorization not working asp net core web api .Net Core MVC - 无法获得406 - 不可接受,总是用Json返回200 OK - .Net Core MVC - cannot get 406 - Not Acceptable, always returns 200 OK with Json ASP.NET 核心异步请求处理程序总是以 200 OK 和空主体响应,如果它是一个单独的方法 - ASP.NET Core async request handler always responds with 200 OK and empty body if it's a separate method 此请求的授权已被拒绝:JWT承载 - Authorization has been denied for this request : JWT Bearer .NET swagger 无 Bearer 前缀的授权 (jwt) - .NET swagger authorization (jwt) without Bearer prefix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM