我正在努力获得一个。Net Core 5 API,具有Auth0。
API不断给我返回“401未授权”。
我正在用Postman Windows应用程序测试API。
我正在使用Visual Studio 2019中的默认API模板WeatherForecast。
调用公共方法/EndPoint工作正常(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
}));
}
}
}