【问题标题】:Issue consuming JWT based Web API .Net Core使用基于 JWT 的 Web API .Net Core 的问题
【发布时间】:2021-04-25 20:22:32
【问题描述】:

即使我在从客户端应用程序到 API 的请求中发送 JWT 令牌,我也无法验证请求。客户端应用程序和 API 均在 .Net Core 5.0 中构建。登录成功,当我从客户端应用程序发送请求时。 API 不对请求进行身份验证。我尝试了很多解决方案,但没有用。我已经使用这个例子实现了 JWT。 https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api 目标框架是 .Net 5.0 API和Client的代码如下。

API 启动代码

    // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors();

            // configure strongly typed settings object
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            // configure DI for application services
            services.AddScoped(provider => new HEDBContext());
            services.AddScoped<IUserService, UserService>();


            //Add JWT Configurations
            var secret = Configuration.GetValue<string>("AppSettings:Secret");

            var key = Encoding.ASCII.GetBytes(secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ClockSkew = TimeSpan.Zero
            };
        });
            services.AddAuthorization();

            services.AddMvc();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
           
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            // custom jwt auth middleware
            app.UseMiddleware<JwtMiddleware>();
          

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
API Controller Code
 [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class SaleContractsController : ControllerBase
    {
        private readonly HEDBContext _context;

        public SaleContractsController(HEDBContext context)
        {
            _context = context;
        }

        // GET: api/SaleContracts
        [HttpGet]
        public async Task<ActionResult<IEnumerable<SaleContract>>> GetSaleContract()
        {
            return await _context.SaleContract.ToListAsync();
        }
}


Client Startup Code
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddMemoryCache();
            services.AddSession();

           
            services.AddControllersWithViews();

            services.AddDbContext<HEClientContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("HEClientContext")));
           
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllersWithViews().AddRazorRuntimeCompilation();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "jwt";
            })
            .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                options.Cookie.Name = "mvcimplicit";
            });
            services.AddAuthorization();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();
            app.UseSession();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Client Controller

     public class SaleContractController : Controller
    {
        private readonly HEClientContext _context;
        APIHelper _helperAPI = new APIHelper();

        public SaleContractController(HEClientContext context)
        {
            _context = context;
        }

        // GET: SaleContract
        public async Task<IActionResult> Index()
        {
            List<SaleContractVM> saleContractVM = new List<SaleContractVM>();

            HttpClient client = _helperAPI.InitializeClient();

            var contentType = new MediaTypeWithQualityHeaderValue(@"application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);
            var token = TempData.Peek("Token").ToString();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JsonConvert.SerializeObject(token, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }));
            

            HttpResponseMessage res = await client.GetAsync("api/SaleContracts");

          

            if (res.StatusCode == HttpStatusCode.Unauthorized)
            {
                ViewBag.Message = "Unauthorized!";
            }
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                saleContractVM = JsonConvert.DeserializeObject<List<SaleContractVM>>(result);

            }
            return View(saleContractVM);
        }}

【问题讨论】:

    标签: asp.net-core-mvc asp.net-core-webapi


    【解决方案1】:

    你试过了吗

     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2017-05-07
      • 2018-09-04
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      相关资源
      最近更新 更多