C# Auth0.netcore5api不断返回401unauthorizerzd

C# Auth0.netcore5api不断返回401unauthorizerzd,c#,auth0,asp.net-core-5.0,C#,Auth0,Asp.net Core 5.0,我正试图用Auth0保护一个.NETCore5API。 但是我有一些困难。我正在写这张表格,几天都没有成功 API不断返回我“401未经授权”。 我正在用Postman Windows应用程序测试API 目前,我正在处理VisualStudio2019的默认API模板WeatherForecast 调用公共方法/端点可以正常工作(http://localhost:20741/WeatherForecast/public) 我向邮递员索要代币,我将其作为不记名代币提供给GET请求。 但当我打电话给

我正试图用Auth0保护一个.NETCore5API。 但是我有一些困难。我正在写这张表格,几天都没有成功

API不断返回我“401未经授权”。 我正在用Postman Windows应用程序测试API

目前,我正在处理VisualStudio2019的默认API模板WeatherForecast

调用公共方法/端点可以正常工作(http://localhost:20741/WeatherForecast/public)

我向邮递员索要代币,我将其作为不记名代币提供给GET请求。 但当我打电话给私人终点站(http://localhost:20741/WeatherForecast/private) 我一直收到401错误

我已经从Auth0网站下载了示例.NETCore3.0项目,私有或公共端点工作正常。我在这两个项目上使用相同的受众和权威。 我认为它与.NETCore5配置或其他东西有关

谁能帮帮我吗

下面是一些代码:

namespace AuthWebApplication1
{
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.OpenApi.Models;
    using WebAPIApplication;

    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)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "AuthWebApplication1", Version = "v1" });
            });


            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder =>
                    {
                        builder
                            .WithOrigins("http://localhost:3000", "http://localhost:4200")
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                    });
            });

            string domain = $"https://dev-***2b.us.auth0.com/";
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = domain;
                    options.Audience = "https://localhost:44349/";
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("read:messages", policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
            });

            // register the scope authorization handler
            services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
        }

        // 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();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AuthWebApplication1 v1"));
            }

            app.UseRouting();

            app.UseCors("AllowSpecificOrigin");
            app.UseStaticFiles();

            app.UseAuthorization();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

命名空间AuthWebApplication1
{
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用Microsoft.OpenApi.Models;
使用webapi应用程序;
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddSwaggerGen(c=>
{
c、 SwaggerDoc(“v1”,新OpenApiInfo{Title=“AuthWebApplication1”,Version=“v1”});
});
services.AddCors(选项=>
{
options.AddPolicy(“AllowSpecificCorigin”,
生成器=>
{
建设者
.来源(“http://localhost:3000", "http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
字符串域=$”https://dev-***2b.us.auth0.com/”;
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>
{
选项。权限=域;
选项。观众=”https://localhost:44349/";
});
services.AddAuthorization(选项=>
{
options.AddPolicy(“读取:消息”,策略=>policy.Requirements.Add(新的HasScopeRequirement(“读取:消息”,域)));
});
//注册范围授权处理程序
services.AddSingleton();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c=>c.SwaggerEndpoint(“/swagger/v1/swagger.json”,“authWebApplication1v1”);
}
app.UseRouting();
应用程序UseCors(“AllowSpecificCorigin”);
app.UseStaticFiles();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
}
这是我的控制器的样子

namespace AuthWebApplication1.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }


        [HttpGet]
        [Route("public")]
        public IActionResult Public()
        {
            return Ok(new
            {
                Message = "Hello from a public endpoint! You don't need to be authenticated to see this."
            });
        }

        [HttpGet]
        [Route("private")]
        [Authorize]
        public IActionResult Private()
        {
            return Ok(new
            {
                Message = "Hello from a private endpoint! You need to be authenticated to see this."
            });
        }

        [HttpGet]
        [Route("private-scoped")]
        [Authorize("read:messages")]
        public IActionResult Scoped()
        {
            return Ok(new
            {
                Message = "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."
            });
        }

        [HttpGet("claims")]
        public IActionResult Claims()
        {
            return Ok(User.Claims.Select(c =>
                new
                {
                    c.Type,
                    c.Value
                }));
        }
    }
}

命名空间AuthWebApplication1.控制器
{
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.Extensions.Logging;
[ApiController]
[路线(“[控制器]”)]
公共类WeatherForecastController:ControllerBase
{
私有静态只读字符串[]摘要=新[]
{
“冻结”、“支撑”、“寒冷”、“凉爽”、“温和”、“温暖”、“温和”、“炎热”、“闷热”、“灼热”
};
专用只读ILogger\u记录器;
公共天气预报控制器(ILogger记录器)
{
_记录器=记录器;
}
[HttpGet]
公共IEnumerable Get()
{
var rng=新随机数();
返回可枚举的范围(1,5)。选择(索引=>NewWeatherForecast
{
日期=DateTime.Now.AddDays(索引),
温度c=下一个温度(-20,55),
摘要=摘要[rng.Next(摘要长度)]
})
.ToArray();
}
[HttpGet]
[路线(“公共”)]
public IActionResult public()
{
返回Ok(新的
{
Message=“来自公共端点的您好!您不需要经过身份验证就可以看到此消息。”
});
}
[HttpGet]
[路线(“私人”)]
[授权]
public IActionResult Private()
{
返回Ok(新的
{
Message=“来自私有端点的您好!您需要经过身份验证才能看到此消息。”
});
}
[HttpGet]
[路由(“专用范围”)]
[授权(“阅读:信息”)]
公共IActionResult作用域()
{
返回Ok(新的
{
Message=“来自私有终结点的您好!您需要经过身份验证并具有read:messages的作用域才能看到此消息。”
});
}
[HttpGet”(“索赔
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   // More Code ..

   //*************************
   // replace this
   app.UseEndpoints(endpoints =>
   {
        endpoints.MapControllers();
   });
   //*************************

   //*************************
   // with this
   app.UseMvc(routes =>
   {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
   });
   //*************************
   // some more code
}
public void ConfigureServices(IServiceCollection services)
{
   // some code
   //*************************
   // add this
   services.AddMvc(x => x.EnableEndpointRouting = false);
   //*************************
   // some more code
}