本文介绍了如何授权Controller .NET Core API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm able to generate tokens succesfully when user login the app.But after I added [Authorize] on my controller,that token comes from header cannot pass the authorization.On Postman returns Unauthorized even though sending up-to date token in header to controller.Before added [Authorize] that worked very well

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
            });
        }

        }

推荐答案

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


app.UseRouting();
app.UseAuthentication(); // add this line. NOTE The order is important.
app.UseAuthorization();
// ... other middlewares

这篇关于如何授权Controller .NET Core API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 06:52