首页 > 解决方案 > 如何将 Auth0 与 .net 核心 API 和 Angular 一起使用?

问题描述

我的问题

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

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

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

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

我的 appsettings.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");
                }
            });
        }
    }

我的 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."
            });
        }

    }

注意:我的解决方案中也有HasScopeHandlerHasScoreRequirement.cs

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

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

标签: angularasp.net-coreauth0

解决方案


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

Authorization: token_type + " " + access_token;

推荐阅读