JWT始终在.net Core API上返回未经授权的401

时间:2019-12-03 11:06:02

标签: c# asp.net api core

我已经实现了jwt来授权.net core 2.2中的Web api。 我成功获取了令牌并将其传递给标头,但总是收到未授权错误。

我是基本用户,我将凭据发送到API进行身份验证。作为交换,我收到了JWT令牌,但是我没有关于用户的任何信息,因为只有服务器才具有能够解码JWT令牌的密钥。那么服务器是否需要向我发送例如用户的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();
        }

1 个答案:

答案 0 :(得分:1)

我认为您错过了添加UseCors的方法,请尝试将以下代码添加到您的startup.cs配置方法中。

library(osmdata)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
library(tidyverse)

lake_gva <-
  getbb("Geneva") %>% 
  opq()%>%
  add_osm_feature(key = "natural", value = "water") %>%
  osmdata_sp()

lake_gva$osm_multipolygons@data$id <- rownames(lake_gva$osm_multipolygons@data)
df_lake_gva <- 
  fortify(lake_gva$osm_multipolygons, region = "id") %>% 
  merge(lake_gva$osm_multipolygons@data, by = "id")
#> Warning in RGEOSUnaryPredFunc(spgeom, byid, "rgeos_isvalid"): Self-intersection
#> at or near point 6.2434241000000004 46.174487800000001
#> SpP is invalid
#> Warning in rgeos::gUnaryUnion(spgeom = SpP, id = IDs): Invalid objects found;
#> consider using set_RGEOS_CheckValidity(2L)

ggplot() +
  geom_polygon(
    data = df_lake_gva,
    aes(x = long, y = lat, group = group)
  )