【问题标题】:How to Authorize Controller .NET Core API如何授权控制器 .NET Core API
【发布时间】:2020-04-15 23:47:05
【问题描述】:

当用户登录应用程序时,我能够成功生成令牌。但是在我的控制器上添加[Authorize] 后,来自标头的令牌无法通过授权。即使发送最新的令牌,邮递员也会返回未经授权在控制器的标头中。在添加 [Authorize] 之前效果很好

Startup.cs

      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.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllers().AddNewtonsoftJson(opt => {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
        services.AddCors();
        services.AddAutoMapper(typeof(AppointmentRepository).Assembly);
        services.AddScoped<IHospitalRepository, HospitalRepository>();
        services.AddScoped<IAppointmentRepository, AppointmentRepository>();
        services.AddScoped<IPatientRepository, PatientRepository>();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
   {
       options.TokenValidationParameters = new TokenValidationParameters
       {
           ValidateIssuerSigningKey = true,
           IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
           .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
           ValidateIssuer = false,
           ValidateAudience = false
       };
   });
        services.AddControllers();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseCors(x => x.WithOrigins().AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

控制器中的登录方法

  [HttpPost("login")]

        public async Task<IActionResult> Login(PatientLoginDto patientLoginDto)
        {
            //if user exists or not
            var patientFromRepo = await _repo.Login(patientLoginDto.IdentityNumber, patientLoginDto.Password);

            if (patientFromRepo == null)
            { return Unauthorized(); }

            var claims = new[]
            {
                //Token has two claim username and id
                new Claim(ClaimTypes.NameIdentifier,patientFromRepo.Id.ToString()),
                new Claim(ClaimTypes.NameIdentifier,patientFromRepo.Name)
            };

            //key generated
            var key = new SymmetricSecurityKey(Encoding.UTF8
                .GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                //passing claims
                Subject = new ClaimsIdentity(claims),
                //expiry date in hours
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            //storing token here(based on token  descriptor object)
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var patient = _mapper.Map<PatientLoggedinDto>(patientFromRepo);

            return Ok(new
            {
                //as response send back to the client
                token = tokenHandler.WriteToken(token),
                patient
            });
        }

        }

【问题讨论】:

  • 1.你添加了UseAuthentication() 吗? 2. 如果你这样做了,你能包括 Startup.cs 吗? 3、你说“不能通过授权”,你得到了什么? 4. 给我们看看payload就好了
  • @itminus 我已经更新了我的 startup.cs 。您可以看到我已经添加了授权。我希望我可以向您展示播放负载,但是当我调试具有 [Authorize] 的控制器时,它无法通过该装饰器。似乎它没有收到我通过 Postman 中的标头传递的令牌。我将添加来自 postman 的响应和错误的屏幕截图

标签: asp.net-core jwt


【解决方案1】:

你需要在app.UseAuthorization();之前注册AuthenticationMiddleware

app.UseRouting(); app.UseAuthentication(); // 添加这一行。注意 顺序 很重要。 app.UseAuthorization(); // ... 其他中间件

【讨论】:

  • 非常感谢。我知道我忘记了一些东西。那行得通!
  • 确实,useAuthentification 优于 UseAuthorization 的顺序非常重要!具有 [Authorize] 属性的端点返回 401。丢失了几个小时,与 Postman 一起检查和重新检查,然后才注意到启动版本中的反转。
猜你喜欢
  • 2018-01-29
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2020-02-11
  • 2023-04-09
  • 2023-01-19
相关资源
最近更新 更多