C# ASP.NET核心授权属性不适用于jwt
我想在ASP.NET Core 3.1中实现基于JWT的安全性。当我使用VisualStudio并从那里运行api项目时,我的代码正在工作。但是当我打算使用dotnetcliC# ASP.NET核心授权属性不适用于jwt,c#,jwt,http-status-code-401,asp.net-core-3.0,C#,Jwt,Http Status Code 401,Asp.net Core 3.0,我想在ASP.NET Core 3.1中实现基于JWT的安全性。当我使用VisualStudio并从那里运行api项目时,我的代码正在工作。但是当我打算使用dotnetclidotnetrun从VS-Code运行项目时,我的登录方法只起作用,我可以在cookie中看到令牌,但我的api的其余部分(如获取用户)将未经授权的401提供给我 链接如下: Visual Studio: VS代码: Startup.cs using System; using System.Collections.Ge
dotnetrun
从VS-Code运行项目时,我的登录方法只起作用,我可以在cookie中看到令牌,但我的api的其余部分(如获取用户)将未经授权的401提供给我
链接如下:
- Visual Studio:
- VS代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace DatingApp.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) {
// Register the Swagger generator, defining 1 or more Swagger documents
//services.AddSwaggerGen(c =>
//{
// c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
//});
services.AddSwaggerGen (c => {
c.SwaggerDoc ("v1", new OpenApiInfo {
Title = "Dating App API",
Version = "v1"
});
c.AddSecurityDefinition ("Bearer", new OpenApiSecurityScheme {
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement (new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
services.AddMvc ().SetCompatibilityVersion (CompatibilityVersion.Version_3_0);
services.AddDbContext<DataContext> (x => x.UseSqlite (Configuration.GetConnectionString ("DefaultConnection")));
services.AddCors (options => {
options.AddPolicy ("CorsPolicy",
builder => builder.AllowAnyOrigin ()
.AllowAnyMethod ()
.AllowAnyHeader ());
});
services.Configure<CloudinarySettings> (Configuration.GetSection ("CloudinarySettings"));
services.AddAutoMapper (typeof (DatingRepository).Assembly);
services.AddScoped<IAuthRepository, AuthRepository> ();
services.AddScoped<IDatingRepository, DatingRepository> ();
services.AddAuthentication (JwtBearerDefaults.AuthenticationScheme)
.AddCookie (cfg => cfg.SlidingExpiration = true)
.AddJwtBearer (options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey (Encoding.ASCII
.GetBytes (Configuration.GetSection ("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// 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 ();
} else {
app.UseExceptionHandler (builder => {
builder.Run (async context => {
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature> ();
if (error != null) {
context.Response.AddApplicationError (error.Error.Message);
await context.Response.WriteAsync (error.Error.Message);
}
});
});
// 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.UseSwagger ();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI (c => {
c.SwaggerEndpoint ("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
// app.UseHttpsRedirection();
app.UseRouting ();
app.UseCors ("CorsPolicy");
app.UseAuthentication ();
app.UseAuthorization ();
app.UseEndpoints (endpoints => {
endpoints.MapControllers ().RequireCors ("CorsPolicy");
});
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用系统文本;
使用System.Threading.Tasks;
使用自动制版机;
使用DatingApp.API.Data;
使用DatingApp.API.Helpers;
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Diagnostics;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.HttpsPolicy;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用Microsoft.Extensions.Logging;
使用Microsoft.Extensions.Options;
使用Microsoft.IdentityModel.Tokens;
使用Microsoft.OpenApi.Models;
命名空间DatingApp.API{
公营创业{
公共启动(IConfiguration配置){
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务){
//注册招摇过市生成器,定义一个或多个招摇过市文档
//services.AddSwaggerGen(c=>
//{
//c.SwaggerDoc(“v1”,新的openapinfo{Title=“myapi”,Version=“v1”});
//});
services.AddSwaggerGen(c=>{
c、 SwaggerDoc(“v1”),新OpenApiInfo{
Title=“约会应用程序API”,
Version=“v1”
});
c、 AddSecurityDefinition(“载体”),新的OpenApiSecurityScheme{
In=参数位置.Header,
Description=“请在字段中插入带持票人的JWT”,
Name=“授权”,
类型=SecuritySchemeType.ApiKey
});
c、 AddSecurityRequest(新的OpenAPISecurityRequest{
{
新的OpenApiSecurityScheme{
Reference=新的OpenApiReference{
Type=ReferenceType.SecurityScheme,
Id=“持票人”
}
},
新字符串[]{}
}
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext(x=>x.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”));
services.AddCors(选项=>{
options.AddPolicy(“CorsPolicy”,
builder=>builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
Configure(Configuration.GetSection(“CloudinarySettings”);
services.AddAutoMapper(typeof(DatingRepository).Assembly);
services.AddScoped();
services.AddScoped();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddCookie(cfg=>cfg.SlidingExpiration=true)
.AddJwtBearer(选项=>{
options.TokenValidationParameters=新的TokenValidationParameters{
ValidateSuersigningKey=true,
IssuerSigningKey=新的SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection(“AppSettings:Token”).Value)),
validateisuer=false,
ValidateAudience=false
};
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境){
if(env.IsDevelopment()){
app.usedeveloperceptionpage();
}否则{
app.UseExceptionHandler(生成器=>{
运行(异步上下文=>{
context.Response.StatusCode=(int)HttpStatusCode.InternalServerError;
var error=context.Features.Get();
if(错误!=null){
context.Response.AddApplicationError(error.error.Message);
wait context.Response.WriteAsync(error.error.Message);
}
});
});
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
//app.UseHsts();
}
app.UseSwagger();
//使中间件能够服务于swagger ui(HTML、JS、CSS等),
//指定Swagger JSON端点。
app.UseSwaggerUI(c=>{
c、 SwaggerEndpoint(“/swagger/v1/swagger.json”,“我的API v1”);
c、 RoutePrefix=string.Empty;
});
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(“公司政策”);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>{
endpoints.mapController().RequireCors(“CorsPol