【问题标题】:.NET CORE 2.1 JWT Bearer Authorization not invoked on request - Always returns 200 OK.NET CORE 2.1 JWT Bearer Authorization 未按请求调用 - 始终返回 200 OK
【发布时间】:2019-03-15 10:52:04
【问题描述】:

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

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

My console

我已经查看了这个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();
    }

【问题讨论】:

  • 中间件的顺序很重要 - 尝试在配置的前面添加身份验证
  • 尝试了这个没有任何运气
  • 我找到了一个(坏的)解决方案。我创建了一个新项目,并将旧项目中的所有内容复制到新项目中。授权立即生效!我不知道出了什么问题,也许我的一些导入错误或什么......?

标签: c# jwt


【解决方案1】:
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"]))
                };
            });

试试这对我有用。

【讨论】:

  • 尝试简要说明您的解决方案提供了什么
【解决方案2】:

使用 Mvc Core 2.2 而不是使用 services.AddAuthorization();services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters().AddAuthorization(); 全部放在一条链中。

【讨论】:

  • 谢谢伙计,你拯救了我的一天!
  • 您能否详细说明所提到的方法和您提供的答案有何不同?
【解决方案3】:

您好像忘记添加授权了。

就像@ste-fu 说的,试着在 services.AddAuthentication(..); 下添加这个;

services.AddAuthorization();

【讨论】:

  • 我试过了,但没用。我还尝试将 AddAuthentication(..) 和 AddAuthorization 放在顶部 - 也没有成功
  • @Alexander 我确实喜欢 Avrohom 的建议,它对我有用。首先是 AddAuthorization(),然后是 AddAuthentication()。也不要忘记调用 app.UseAuthentication();在配置中。
猜你喜欢
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多