如何设置Swagger以通过授权测试WebAPI

时间:2018-07-23 10:42:44

标签: asp.net-web-api identityserver4 swagger-ui

我在使用基于eShopOnContainer的身份服务器在Web API中设置摇摇晃晃时遇到问题。

我可以加载swagger页面及其api。我在内存客户端中有客户端,并且在身份服务器中测试了用户。迅速的界面上有一个“授权”按钮,我可以单击它并显示一个对话框,允许我输入客户端ID和可选范围。单击“授权”按钮后,将弹出一个新的浏览器,并显示错误页面/ home / error ....

    Error.
An error occurred while processing your request.
Request ID: 0HLFGGIKSCIL5:00000002 
Development Mode
Swapping to Development environment will display more detailed information about the error that occurred. 
Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application. 

© 2018 - Identity.API

WebApi设置:

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title = "FamBam - Parent Side HTTP API",
                    Version = "v1",
                    Description = "The Parent Side Microservcie HTTP API",
                    TermsOfService = "Term Of Service"
                });
                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
                    TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
                    Scopes = new Dictionary<string, string>()
                    {
                        { "api", "Read access to protected resources" }
                    }
                });

                options.OperationFilter<AuthorizeCheckOperationFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

            //services.AddCustomMvc(Configuration)
            //    .AddCustomAuthentication(Configuration);
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            var identityUrl = Configuration.GetValue<string>("urls:identity");
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(options =>
            {
                options.Authority = Configuration.GetValue<string>("IdentityUrlExternal");
                options.RequireHttpsMetadata = false;
                options.Audience = "parent.api.gateway";              
                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = async ctx =>
                    {
                        int i = 0;
                    },
                    OnTokenValidated = async ctx =>
                    {
                        int i = 0;
                    }
                };
            });

            services.AddMvc(); 

Identity Server 4设置:

// configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                //.AddDeveloperSigningCredential()               
                .AddTestUsers(Config.GetUsers())
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

测试客户端设置

 new Client
                {
                    ClientId = "parent.api.gateway",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,

                    RedirectUris = { "http://localhost:5100/swagger/oauth2-redirect.html" },
                    PostLogoutRedirectUris = { "http://localhost:5100/swagger/" },

                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes =
                    {
                        "api1"
                    }
                },

更新:基于顶部代码。我删除了AddAspIdentity,ClientSecret并更新了Scope =“ api1”,我在最后错过了1。现在,它没有任何错误地转到身份服务器登录页面。我输入了电子邮件和密码。这次我收到与数据库远程连接有关的错误。那就是我的想法。 我当前正在使用本地数据库:

Data Source=DESKTOP-8HA0TJO;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

我已经在内存中有测试用户,如上面的代码所示。我是否需要配置数据库以供远程使用?该怎么做?

0 个答案:

没有答案