如何将 Auth0 与 .net 核心 API 和 Angular 一起使用?
Posted
技术标签:
【中文标题】如何将 Auth0 与 .net 核心 API 和 Angular 一起使用?【英文标题】:How can I use Auth0 with .net core API and Angular? 【发布时间】:2020-10-26 01:13:27 【问题描述】:我的问题
我正在尝试使用 Auth0 使用 Angular 和 asp.net 核心创建一个基本登录页面,但我不知道这一切是如何工作的......我尝试在使用 Postman 将其连接到 Angular 之前测试我的 API 和每次我在邮递员上收到 Bearer error="invalid_token" 时,即使我使用了好的令牌。
还有
文档示例仅返回带有 Controller(Api 端点) 的消息“Hello world”,我什至不知道我应该在之后放置什么来将我的控制器和 Angular 服务连接在一起,我迷失在所有这些代码中......
这是我正在寻找的文档.net core、Angular,然后用Postman 测试API。
请帮助我,感谢您未来的回答!
我的 appsettings.json
"Auth0":
"Domain": "dev-icv0769a.us.auth0.com",
"ApiIdentifier": "https://localhost:44398/api/Login/private"
我的 Startup.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");
);
我的 LoginController.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 和 HasScoreRequirement.cs。
Postman response with the error message
如果您需要其他帮助我,请尽管提出,再次感谢!
【问题讨论】:
检查您的 ASP.NET Core 服务器日志以获取有关身份验证失败的详细信息。 在哪里可以找到这些日志? 【参考方案1】:您必须在每个请求中提供 Authorization 标头才能访问 Private()
方法:
Authorization: token_type + " " + access_token;
【讨论】:
我做到了,但它不起作用,所以我对 JWT 采取了另一种方法,它终于起作用了!但我感谢您的帮助,谢谢您 从您的屏幕截图来看,Postman 中似乎缺少 Authorization 标头,无论如何,快乐编码以上是关于如何将 Auth0 与 .net 核心 API 和 Angular 一起使用?的主要内容,如果未能解决你的问题,请参考以下文章
如何将 django rest api 中的用户与 Auth0 同步
AzureAD 的 JWT 在 .NET 核心 API 中提供 403 Forbidden