asp.net - 更新我的 identityserver4 后不断收到无效范围错误

标签 asp.net validation identityserver4

我让 identityProviderService 与我的 API 和 Web 应用程序一起工作,然后我更新我更新了我的依赖项(identityServer4),这导致我使用代码或混合时不断出现以下错误。

IdentityServer4 Error: Invalid_scope


我检查了日志,范围很好,但我可以解决为什么我一直收到这个错误!详情如下:
我的本地 Idp (Identityserver4) 日志和主要错误 =>
IdentityServer4.Hosting.IdentityServerMiddleware: Information:
Invoking IdentityServer endpoint:
IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
IdentityServer4.Validation.DefaultResourceValidator: Error: Scope
Bd.Web.Api not found in store.
IdentityServer4.Endpoints.AuthorizeEndpoint: Error: Request validation
failed IdentityServer4.Endpoints.AuthorizeEndpoint: Information: {  
"ClientId": "BdWebAppClientId",   "ClientName": "Bd web Client
Application",   "RedirectUri": "https://localhost:xxxxx/signin-oidc", 
"AllowedRedirectUris": [
    "https://localhost:44386/signin-oidc"   ],   "SubjectId": "anonymous",   "ResponseType": "code",   "ResponseMode": "form_post", 
"GrantType": "authorization_code",   "RequestedScopes": "openid
profile Bd.Web.Api",   "State":
"CfDJ8Foioa24zShFmzIFmkTbGBTrbiiEwQYmHGMRUN7FwsfKMgY2-olWJA1XVlAkA0uCWIR6HhMdu2X1exzVKTNFTcAD456Z0r3es5ki377uBEJgjA9jmyQFWWzTZV6_7GEmIC39xUh_b_YAqXgtzO0olZ52beNFuxruk_NshL47NhwcaETCH2cy3XTvRN0NTxZHmxVWglo13iSE7RVpNghHc7pBW7jCv7cB2RldQnEvsJ4s56AdiICw9sdKEJ5mQNoXngshanycX4MmD3qaW0TX6knY43pAqMuPgEEVqd7BXKt_koQfiQuAP3pQNbsyOAb1jtoZ8egUHiKgXjofs8ci2i4",
"PromptMode": "",   "Raw": {
    "client_id": "BdWebAppClientId",
    "redirect_uri": "https://localhost:xxxxx/signin-oidc",
    "response_type": "code",
    "scope": "openid profile Bd.Web.Api",
    "response_mode": "form_post",
    "nonce": "637284460180108591.ZjIxYjhlZGEtYjk0Mi00M2UxLWExNWItOGYzMjhjODEyMGQzZmU5NjZmZDAtOTQwYi00YTFlLWJlMWUtM2U3YzBhM2NmNjQ4",
    "state": "CfDJ8Foioa24zShFmzIFmkTbGBTrbiiEwQYmHGMRUN7FwsfKMgY2-olWJA1XVlAkA0uCWIR6HhMdu2X1exzVKTNFTcAD456Z0r3es5ki377uBEJgjA9jmyQFWWzTZV6_7GEmIC39xUh_b_YAqXgtzO0olZ52beNFuxruk_NshL47NhwcaETCH2cy3XTvRN0NTxZHmxVWglo13iSE7RVpNghHc7pBW7jCv7cB2RldQnEvsJ4s56AdiICw9sdKEJ5mQNoXngshanycX4MmD3qaW0TX6knY43pAqMuPgEEVqd7BXKt_koQfiQuAP3pQNbsyOAb1jtoZ8egUHiKgXjofs8ci2i4",
    "x-client-SKU": "ID_NETSTANDARD2_0",
    "x-client-ver": "5.5.0.0"   }

我的配置包括三个类 User、Resources 和 Client,如下所示:
public class Users
{
    public static List<TestUser> Get()
    {
        return new List<TestUser> {
            new TestUser {
                SubjectId = "5BE86359-073C-434B-AD2D-A3932222DABE",
                Username = "scott",
                Password = "password",
                Claims = new List<Claim> {
                    new Claim(JwtClaimTypes.Email, "scott@scottbrady91.com"),
                    new Claim(JwtClaimTypes.Role, "admin")
                }
            }
        };
    }
}


public class Resources
{
    public static  IEnumerable<IdentityResource> Ids()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Address()
        };
    }


    public static IEnumerable<ApiResource> Apis()
    {
        return new List<ApiResource>
        {
            new ApiResource("Bd.Web.Api", "Bd Web Api") {
                Description = "BD API Access",
                //UserClaims = new List<string> {"role"},
                ApiSecrets = new List<Secret> {new Secret("secret".Sha256())}
            }
        };
    }

}


public class Clients
{
    public static IEnumerable<Client> Get()
    {
        return new List<Client> {
            new Client {
                ClientId = "BdWebAppClientId",
                ClientName = "Bd web Client Application",
                AllowedGrantTypes = GrantTypes.Code,
                RequirePkce = false,
                ClientSecrets = new List<Secret> {
                    new Secret("secret".Sha256())},
                AllowedScopes = 
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Address,
                    "Bd.Web.Api"
                },
                RedirectUris =  new List<string>{"https://localhost:44386/signin-oidc"},
                PostLogoutRedirectUris = new List<string>{ "https://localhost:44386/sigout-callback-oidc" }
            
            }

        };
    }
}


public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllersWithViews();

        services.AddIdentityServer()
            .AddInMemoryClients(Clients.Get())
            .AddInMemoryIdentityResources(Resources.Ids())
            .AddInMemoryApiResources(Resources.Apis())
            .AddTestUsers(Users.Get())
            .AddDeveloperSigningCredential();
    }

    // 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.UseRouting();

        app.UseIdentityServer();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            //endpoints.MapGet("/", async context =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        });
    }
}
我的网络应用程序启动如下:
 public class Startup
 {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        }

        public IConfiguration Configuration { get; }

            services.Configure<CookiePolicyOptions>(options =>
            {

                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
            });
            

            services.AddMvc(options => { options.EnableEndpointRouting = false; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddHttpContextAccessor();

            services.AddTransient<BearerTokenHandler>();

            services.AddHttpClient("ApiClient", client =>
            {
                //client.BaseAddress = new Uri("https://bandapi.azurewebsites.net/api/");
                client.BaseAddress = new Uri("https://localhost:44301/api/");
                //client.BaseAddress = new Uri("https://192.168.1.25:44301/api/");
                client.Timeout = new TimeSpan(0, 0, 30);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
                
               

            }).AddHttpMessageHandler<BearerTokenHandler>();

            services.AddHttpClient("IdpClient", client =>
            {

                client.BaseAddress = new Uri("https://localhost:xxxxx/");
                client.Timeout = new TimeSpan(0, 0, 30);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
            }).AddHttpMessageHandler<BearerTokenHandler>();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "BdWebAppCookies";
                options.DefaultChallengeScheme = "oidc";


                //options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                //options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
         .AddCookie("BdWebAppCookies"  /*CookieAuthenticationDefaults.AuthenticationScheme*/, options =>
         {
             options.AccessDeniedPath = "/Authentication/AccessDenied";
         })
         .AddOpenIdConnect("oidc" /*OpenIdConnectDefaults.AuthenticationScheme*/, options =>
         {

             options.Authority = "https://localhost:xxxx/";
             //options.RequireHttpsMetadata = true;
             options.ClientId = "BdWebAppClientId";

             
             options.Scope.Add("openid");
             options.Scope.Add("profile");
             options.Scope.Add("address");

             options.Scope.Add("Bd.Web.Api");

             
             options.ClientSecret = "secret";
             options.ResponseType = "code";
             options.UsePkce = false;
             options.SignInScheme = "BdWebAppCookies";
            
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
   }

最佳答案

在 IdentityServer4 4.x 中,api 范围的处理发生了变化。现在您需要定义所有可用的 api 范围并将它们提供给配置。
更新的文档显示了它是如何完成的。 https://identityserver4.readthedocs.io/en/latest/topics/resources.html#scopes

public static IEnumerable<ApiScope> GetApiScopes()
{
    return new List<ApiScope>
    {
        new ApiScope(name: "read",   displayName: "Read your data."),
        new ApiScope(name: "write",  displayName: "Write your data."),
        new ApiScope(name: "delete", displayName: "Delete your data.")
    };
}
然后将范围添加到您的 IdentityServer 配置中:
    services.AddIdentityServer()
        .AddInMemoryApiScopes(Config.GetApiScopes());
此外,您需要将范围添加到已定义的 ApiResources 中,如下所述:https://identityserver4.readthedocs.io/en/latest/topics/resources.html#api-resources
public static readonly IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("invoices", "Invoice API")
        {
            Scopes = { "invoice.read", "invoice.pay", "manage" }
        },

        new ApiResource("customers", "Customer API")
        {
            Scopes = { "customer.read", "customer.contact", "manage" }
        }
    };
}

关于asp.net - 更新我的 identityserver4 后不断收到无效范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62521583/

相关文章:

javascript,限制文本字段中的字符数

IdentityServer4 - 删除过期的持久授权

authentication - IdentityServer4 client_id 特定的登录页面

c# - 使用未知名称/参数数量更新 sql 语句

php - 仅正整数的正则表达式是什么? (零是不允许的)

jquery - 获取选中的checkboxlist列表项值

jquery - 在执行 jquery ajax post 时,如何从我的 asp.net mvc Controller 返回错误?

.net-core - 在使用身份服务器 4 .Net core 2.0 的客户端中未访问自定义声明

c# - 如何在 ASP.NET Core 2.0 Razor 页面中填充下拉列表

asp.net - 如何使用 ASP.NET 调用 Web 服务(.wsdl)