ASP.NET CORE REST API(401未经授权)

问题描述 投票:-2回答:1

我在用ASP.NET CORE进行REST API发布时遇到麻烦。

当我在本地主机中调试代码时,就可以了。

但是当我想在IIS 10.0中发布它时,我可以导航到敏捷的UI。

但是,如果我想使用允许匿名授权的Get方法,则会出现401错误。

[请帮助这个贫穷而初级的灵魂。如果您需要更多信息,请询问我

c# .net api iis http-status-code-401
1个回答
0
投票

我正在使用JwtBearer,这是我的startup.cs代码:


 public class Startup
{
    private readonly string _myPolicy = "_myPolicy";
    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)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;

        });



        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidIssuer = "Julien",
                ValidAudience = "Gonelec",
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Llave_super_secreta"])),
                ClockSkew = TimeSpan.Zero
            };
        });
        services.Configure<MvcOptions>(options => options.Filters.Add(new CorsAuthorizationFilterFactory(_myPolicy)));

        services.AddSwaggerGen(config =>
        {
            config.SwaggerDoc("V1", new Info
            {
                Title = "MiApi",
                Version = "V1",

            });
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        ConfigurationService(services);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(config =>
        {
            config.SwaggerEndpoint("/swagger/V1/swagger.json", "MiApiV1");
            config.OAuthUseBasicAuthenticationWithAccessCodeGrant();
        });
        app.Use(next => async context => {
            try
            {
                await next(context);
            }

            catch
            {
                // If the headers have already been sent, you can't replace the status code.
                // In this case, throw an exception to close the connection.
                if (context.Response.HasStarted)
                {
                    throw;
                }

                context.Response.StatusCode = 401;
            }
        });
        app.UseAuthentication();

        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.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller-home}/{action = Index}/{id?}");
        });


        app.UseMvc();
    }
}

此外,如果您对我的代码有任何建议,欢迎您。

© www.soinside.com 2019 - 2024. All rights reserved.