我已经在 .net core 2.2 中实现了 jwt 来授权 web api。 我已成功获取 token 并将其传递给 header ,但始终出现未授权错误。
我是基本用户,我将我的凭据发送到 API 进行身份验证。作为交换,我收到了一个 JWT token ,但我没有关于用户的任何信息,因为只有服务器具有能够解码 JWT token 的 key 。那么服务器是否需要向我发送例如用户 ID,以便我可以调用我的 api 用户/ID 来检索有关已验证用户的信息?
我在 startup.cs 中的代码如下
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddTransient<IDbConnection>(db => new
OracleConnection(Configuration.GetConnectionString("abc")));
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new DefaultNamingStrategy() };
});
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Use(async (context, next) =>
{
var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
if (error != null && error.Error is SecurityTokenExpiredException)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
State = "Unauthorized",
Msg = "token expired"
}));
}
else if (error != null && error.Error != null)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
State = "Internal Server Error",
Msg = error.Error.Message
}));
}
//when no error, do next.
else await next();
});
});
app.UseAuthentication();
app.UseMvc();
}
最佳答案
我认为您错过了添加 UseCors,请尝试将以下代码添加到 startup.cs 的配置方法中。
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
关于c# - JWT 总是在 .net 核心 api 上返回未经授权的 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59155703/