c# - JWT 总是在 .net 核心 api 上返回未经授权的 401

标签 c# asp.net-core jwt

我已经在 .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/

相关文章:

sql-server - dotnet ef 数据库更新中与网络相关或特定于实例的错误

.Net core字典中的Mongodb $inc运算符

c# - "services.AddRazorPages();"实际上添加了哪些服务?

c# - Gecko 45 c# winform 添加脚本到文档

c# - XAML:如何更改特定 ResourceDictionary 的来源

c# - 与 UWP 中的应用服务通信时可以使用哪些数据类型

java - 使用 jose4j 验证具有分离负载的 JWS 失败

key - 使用 RSA、私钥和公钥的 Nimbus JOSE JWT 加密

spring-boot - 当 Spring Boot 应用程序使用 nginx Controller 部署到 kubernetes 集群时,JWT 身份验证不起作用

c# - 如何使用 IL Emit 定义相互引用的两种类型