Auth0 .Net Core 5 API 继续返回 401-Unauthorirezd
Auth0 .Net Core 5 API Keep returning 401-Unauthorirezd
我正在尝试使用 Auth0 保护 .Net Core 5 API。
但我有一些困难。几天来我一直在处理这个表格,但没有成功。
API 一直给我返回“401 未经授权”。
我正在使用 Postman Windows App 测试 API。
目前我正在使用 Visual Studio 2019
的默认 API 模板 WeatherForecast
调用 public method/EndPoint 工作正常 (http://localhost:20741/WeatherForecast/public)
我正在向 Postman 请求令牌, 我将作为不记名令牌提供给 GET 请求。
但是当我调用私有端点 (http://localhost:20741/WeatherForecast/private)
我一直收到 401 错误。
我已经从 Auth0 网站和 Private 或 public 端点下载示例 .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
}));
}
}
}
我终于让它正常工作了。
配置方法:
我不得不删除
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
}
如果这对其他人有帮助...
现在我只需要了解这个变化到底意味着什么。任何线索都会很好。
我正在尝试使用 Auth0 保护 .Net Core 5 API。 但我有一些困难。几天来我一直在处理这个表格,但没有成功。
API 一直给我返回“401 未经授权”。 我正在使用 Postman Windows App 测试 API。
目前我正在使用 Visual Studio 2019
的默认 API 模板 WeatherForecast调用 public method/EndPoint 工作正常 (http://localhost:20741/WeatherForecast/public)
我正在向 Postman 请求令牌, 我将作为不记名令牌提供给 GET 请求。 但是当我调用私有端点 (http://localhost:20741/WeatherForecast/private) 我一直收到 401 错误。
我已经从 Auth0 网站和 Private 或 public 端点下载示例 .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
}));
}
}
}
我终于让它正常工作了。
配置方法: 我不得不删除
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
}
如果这对其他人有帮助...
现在我只需要了解这个变化到底意味着什么。任何线索都会很好。