簡體   English   中英

解決無效的 Scope 錯誤身份服務器 6

[英]Resolve Invalid Scope Error Identity Server 6

我是身份服務器的新手,最近為一個項目設置了它,但我不斷收到以下錯誤

抱歉,出現錯誤:invalid_scope Invalid scope

這些是構成應用程序的組件。

Web Client -> AS.NETCORE Razor Pages 應用(端口:7091)

Ocelot -> API 網關

身份服務器 6(端口:5001)

條紋點網 -> API

購物籃 -> API

我的配置/代碼如下:

身份服務器

  public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
               // new IdentityResources.Email(),
            };
        public static IEnumerable<ApiScope> ApiScopes =>
            new List<ApiScope>
            {
                new ApiScope("stripedotnetapi", "StripeDotNet API")
            };
        public static IEnumerable<Client> Clients =>
            new List<Client>
            {            
                // interactive ASP.NET Core MVC client
                new Client
                {
                    ClientId = "razorweb",
                    ClientName = "Razor Web",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.Code,
                
                    // where to redirect to after login
                    RedirectUris = { "https://localhost:7091/signin-oidc" },

                    //FrontChannelLogoutUri = "https://localhost:7091/signout-callback-oidc",

                    // where to redirect to after logout
                    PostLogoutRedirectUris = { "https://localhost:7091/signout-callback-oidc" },

                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                       // IdentityServerConstants.StandardScopes.Email,
                        "stripedotnetapi"
                    }
                }
            };
    }

身份服務器:托管擴展

 builder.Services
                .AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;

                    // see https://docs.duendesoftware.com/identityserver/v6/fundamentals/resources/
                    options.EmitStaticAudienceClaim = true;
                })
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryClients(Config.Clients)
                .AddAspNetIdentity<ApplicationUser>();

條紋點網 API

 public static IServiceCollection AddSecurityServices(this IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.TokenValidationParameters.ValidateAudience = false;
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("scope", "stripedotnetapi");
                });
            });

            return services;
        }

StripeDotNet API: Controller 代碼

[Route("api/[controller]")]
    [Authorize("ApiScope")]
    public class CheckoutController : BaseController
    {
        private readonly ICheckoutService _checkoutService;

        public CheckoutController(ICheckoutService checkoutService)
        {
            _checkoutService = Guard.Against.Null(checkoutService, nameof(checkoutService));
        }

        [HttpGet]
        public async Task<IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var response = await _checkoutService.CreateCheckoutSessionAsync(req.TenantId, req.PriceId,
                req.SuccessUrl, req.CancelUrl);

            return Ok(response);
        }

        [HttpGet("{sessionId}")]
        public async Task<IActionResult> GetCheckoutSession(string sessionId)
        {
            var response = await _checkoutService.GetCheckoutSessionAsync(sessionId);

            return Ok(response);
        }
    }

豹貓 API 網關

var authenticationProviderKey = "IdentityApiKey";
builder.Services.AddAuthentication()
    .AddJwtBearer(authenticationProviderKey, x =>
    {
        x.Authority = "https://localhost:5001"; // IDENTITY SERVER URL
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false
        };
    });

Ocelot API 網關:配置文件

{
  "UpStreamPathTemplate": "/api/Checkout",
  "UpstreamHttpMethod": [ "Get" ],
  "DownstreamScheme": "https",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 7056
    }
  ],
  "DownstreamPathTemplate": "/api/Checkout",
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "IdentityApiKey",
    "AllowedScopes": []
  }
},
{
  "UpStreamPathTemplate": "/api/Checkout/{sessionId}",
  "UpstreamHttpMethod": [ "Get" ],
  "DownstreamScheme": "https",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 7056
    }
  ],
  "DownstreamPathTemplate": "/api/Checkout/{sessionId}",
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "IdentityApiKey",
    "AllowedScopes": []
  }
},

Web 客戶

public static IServiceCollection AddSecurityServices(this IServiceCollection services)
{
    JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "https://localhost:5001";

        options.ClientId = "razorweb";
        options.ClientSecret = "secret";
        options.ResponseType = "code";

        options.Scope.Clear();
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        //options.Scope.Add("email");
        options.Scope.Add("stripedotnetapi");
        options.Scope.Add("offline_access");

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;
    });

    return services;
}

我的發現端點將這些項目顯示為有效范圍

  "scopes_supported": [
    "openid",
    "profile",
    "stripedotnetapi",
    "offline_access"
  ],

支持的范圍似乎已為 web 客戶端正確設置,但我不斷收到無效的 scope 錯誤。 任何指導將不勝感激。

解決了。 我沒有對文檔給予足夠的關注。 未向客戶端授予脫機訪問權限。

AllowOfflineAccess = true,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM