【问题标题】:Auth0 .Net Core 5 API Keep returning 401-UnauthorirezdAuth0 .Net Core 5 API 不断返回 401-Unauthorirezd
【发布时间】:2021-04-05 21:39:55
【问题描述】:

我正在尝试使用 Auth0 保护 .Net Core 5 API。 但我有一些困难。我现在正在处理这个表格,但没有成功。

API 不断返回“401 Unauthorized”。 我正在使用 Postman Windows App 测试 API。

目前我正在搞乱 Visual Studio 2019 中的默认 API 模板 WeatherForecast

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

我正在向 Postman 请求一个令牌,我将作为承载令牌提供给 GET 请求。 但是当我调用私有端点时(http://localhost:20741/WeatherForecast/private) 我不断收到 401 错误。

我已经从 Auth0 网站下载了示例 .Net Core 3.0 项目,并且私有或公共端点工作正常。我在这两个项目上使用相同的受众和权威。 我认为它与 .Net Core 5 配置有关

谁能帮帮我。

这里有一些代码:

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();
            });
        }
    }
}

这是我的控制器的样子

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
                }));
        }
    }
}

【问题讨论】:

    标签: c# auth0 asp.net-core-5.0


    【解决方案1】:

    我终于让它正常工作了。

    配置方法: 我不得不删除

    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
    }
    

    如果这可以帮助其他人......

    现在我只需要了解此更改的确切含义即可。任何线索都会很好。

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 2021-11-12
      • 2020-05-05
      • 2018-07-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      相关资源
      最近更新 更多