Asp.net core mvc 基于JWT的Web API.Net核心的问题
我无法验证请求,即使我正在从客户端应用程序向API发送请求中的JWT令牌。客户端应用程序和API都内置于.Net Core 5.0中。当我从客户端应用发送请求时,登录成功。API不验证请求。我试过很多解决办法,但都没用。我已经用这个例子实现了JWT。 目标框架是.NET5.0 API和客户端的代码如下所示 API启动代码Asp.net core mvc 基于JWT的Web API.Net核心的问题,asp.net-core-mvc,asp.net-core-webapi,Asp.net Core Mvc,Asp.net Core Webapi,我无法验证请求,即使我正在从客户端应用程序向API发送请求中的JWT令牌。客户端应用程序和API都内置于.Net Core 5.0中。当我从客户端应用发送请求时,登录成功。API不验证请求。我试过很多解决办法,但都没用。我已经用这个例子实现了JWT。 目标框架是.NET5.0 API和客户端的代码如下所示 API启动代码 // This method gets called by the runtime. Use this method to add services to the co
// 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);
}}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddCors();
//配置强类型设置对象
services.Configure(Configuration.GetSection(“AppSettings”);
//为应用程序服务配置DI
addScope(provider=>newhedbContext());
services.addScope();
//添加JWT配置
var secret=Configuration.GetValue(“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=新的TokenValidationParameters
{
validateisuer=false,
ValidateAudience=false,
ValidateLifetime=true,
ValidateSuersigningKey=true,
IssuerSigningKey=新对称性安全密钥(密钥),
时钟偏移=时间跨度0
};
});
services.AddAuthorization();
services.AddMvc();
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
//全球cors政策
app.UseCors(x=>x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
//自定义jwt身份验证中间件
app.UseMiddleware();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
API控制器代码
[路由(“api/[控制器]”)]
[授权]
[ApiController]
公共类SaleContractor控制器:ControllerBase
{
私有只读HEDBContext\u上下文;
公共销售合同控制器(HEDBContext上下文)
{
_上下文=上下文;
}
//获取:api/销售合同
[HttpGet]
公共异步任务GetSaleContract()
{
return wait_context.SaleContract.toListSync();
}
}
客户端启动代码
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
services.AddMemoryCache();
services.AddSession();
services.AddControllersWithViews();
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“HEClientContext”));
services.AddSingleton();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddAuthentication(选项=>
{
options.DefaultScheme=CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=“jwt”;
})
.AddCookie(选项=>
{
options.ExpireTimeSpan=TimeSpan.FromMinutes(60);
options.Cookie.Name=“mvcimplicit”;
});
services.AddAuthorization();
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
});
}
客户端控制器
公共类控制器:控制器
{
私有只读HEClientContext\u上下文;
APIHelper _helperAPI=新的APIHelper();
public SaleContractController(HeClient上下文)
{
_上下文=上下文;
}
//获得:销售合同
公共异步任务索引()
{
List saleContractVM=新列表();
HttpClient客户端=_helperAPI.InitializeClient();
var contentType=新的MediaTypeWithQualityHeaderValue(@“应用程序/json”);
client.DefaultRequestHeaders.Accept.Add(contentType);
var token=TempData.Peek(“token”).ToString();
client.DefaultRequestHeaders.Authorization=新的AuthenticationHeaderValue(“承载者”,JsonConvert.SerializeObject(令牌,表单
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);