如何将 Auth0 与 .net core API 和 Angular 一起使用?



My Problem

我正在尝试使用 Auth0 制作一个带有 Angular 和 asp.net 核心的基本登录页面,我不知道这一切是如何工作的......在将 API 连接到带有邮递员的 Angular 之前,我尝试测试我的 API,每次我在邮递员上收到Bearer 错误="invalid_token">时,即使我使用了好的令牌。

文档示例仅返回带有控制器(Api 端点(的消息"Hello world",我什至不知道之后我应该放什么来将我的控制器和 Angular 服务连接在一起,我迷失在所有代码中......

这是我正在寻找.net核心,Angular的文档,然后使用Postman测试API。

请帮助我,感谢您未来的答案!

我的应用设置.json

"Auth0": {
"Domain": "dev-icv0769a.us.auth0.com",
"ApiIdentifier": "https://localhost:44398/api/Login/private"
}

我的创业公司.cs

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.AddControllersWithViews();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddDbContext<CLDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
string domain = $"https://{Configuration["Auth0:Domain"]}/";
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = Configuration["Auth0:ApiIdentifier"];
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
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();
}
else
{
app.UseExceptionHandler("/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.UseHttpsRedirection();
app.UseStaticFiles();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}

我的登录控制器.cs

[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[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("public")]
public IActionResult Public()
{
return Ok(new
{
Message = "Hello from a public endpoint! You don't need to be authenticated to see this."
});
}
}

注意:我的解决方案中还有HasScopeHandler 和 HasScoreRequirements.cs

带有错误消息的邮递员响应

如果您需要其他帮助我的东西,请询问,再次感谢!

您必须在每个请求中提供一个授权标头才能访问Private()方法:

Authorization: token_type + " " + access_token;

最新更新