首页 > 解决方案 > 将 localhost 用于 ASP.NET Core API 时如何停止授权

问题描述

我有一个使用 Okta 进行授权和身份验证的 ASP.NET Core Web API。问题是我正在使用的 Okta 实例使用 CORS 阻止 localhost 请求。如果我们假设我无法改变这一点,这就是我采取的方法:

#if !DEBUG
[Authorize]
#endif
public class ApiValuesController : ControllerBase
{
//stuff
}

在 startup.cs 中:

public void ConfigureServices(IServiceCollection services)
{
     //...
     if (!Environment.IsDevelopment())
     {
         //add authentication
         services.AddAuthentication(options =>
            {
               options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
               options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.Authority = Configuration["Okta:Authority"];
               options.RequireHttpsMetadata = true;
               options.ClientId = Configuration["Okta:ClientId"];
               options.ClientSecret = "LOL No";
               options.ResponseType = OpenIdConnectResponseType.Code;
               options.GetClaimsFromUserInfoEndpoint = true;
               options.Scope.Add("openid");
               options.Scope.Add("profile");
               options.SaveTokens = true;
               options.TokenValidationParameters = new TokenValidationParameters
               {
                    NameClaimType = "name",
                    RoleClaimType = "groups",
                    ValidateIssuer = true
               };
           });
           services.AddAuthorization();
        }
        //...
    }

    public void Configure(IApplicationBuilder app, IHostEnvironment env)
    {
        //...
        if (!env.IsDevelopment())
        {
            //enable authentication
            app.UseAuthentication();
            app.UseAuthorization();
        }
        //...
    }

但是,如果我出于任何原因需要在本地运行我的发布版本,这会导致问题。当然,我有更好的方法可以在不破坏授权的情况下在本地运行发布版本。

感谢大家!

标签: c#asp.net-coreopenid-connect

解决方案


推荐阅读