示例#1
0
        private static List <SchemeRecord> SchemeRecords(Oauth2Section oauth2Section, List <string> schemes)
        {
            var authSchemes = oauth2Section.Authorities.Where(c => schemes.Any(c2 => c2 == c.Scheme));

            List <SchemeRecord> schemeRecords = new List <SchemeRecord>();

            foreach (var authScheme in authSchemes)
            {
                Func <TokenValidatedContext, Task> tokenValidationHandler = context =>
                {
                    ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                    if (identity != null)
                    {
                        // Add the access_token as a claim, as we may actually need it
                        var accessToken = context.SecurityToken as JwtSecurityToken;
                        if (accessToken != null)
                        {
                            identity.AddClaim(new Claim("access_token", accessToken.RawData));
                        }
                    }
                    return(Task.CompletedTask);
                };

                var schemeRecord = new SchemeRecord()
                {
                    Name             = authScheme.Scheme,
                    JwtBearerOptions = options =>
                    {
                        options.Authority                 = authScheme.Authority;
                        options.RequireHttpsMetadata      = false;
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer           = true,
                            ValidateAudience         = false,
                            ValidateLifetime         = true,
                            ValidateIssuerSigningKey = true
                        };
                        options.Events = new JwtBearerEvents
                        {
                            OnMessageReceived = context => Task.CompletedTask,
                            OnTokenValidated  = tokenValidationHandler
                        };
                    }
                };
                schemeRecords.Add(schemeRecord);
            }

            return(schemeRecords);
        }
示例#2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            services.AddObjectContainer();  // use this vs a static to cache class data.
            services.AddOptions();
            services.AddDistributedMemoryCache();
            services.AddGraphQLPlayRollup(this);
            services.AddGraphQLOrders();
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  corsBuilder => corsBuilder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Daffy Duck",
                                  policy => { policy.RequireClaim("client_namespace", "Daffy Duck"); });
            });
            var scheme = Configuration["authValidation:scheme"];

            var section       = Configuration.GetSection("InMemoryOAuth2ConfigurationStore:oauth2");
            var oauth2Section = new Oauth2Section();

            section.Bind(oauth2Section);

            var query = from item in oauth2Section.Authorities
                        where item.Scheme == scheme
                        select item;
            var wellknownAuthority = query.FirstOrDefault();

            var authority = wellknownAuthority.Authority;
            List <SchemeRecord> schemeRecords = new List <SchemeRecord>()
            {
                new SchemeRecord()
                {
                    Name             = scheme,
                    JwtBearerOptions = options =>
                    {
                        options.Authority                 = authority;
                        options.RequireHttpsMetadata      = false;
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer           = true,
                            ValidateAudience         = false,
                            ValidateLifetime         = true,
                            ValidateIssuerSigningKey = true
                        };
                        options.Events = new JwtBearerEvents
                        {
                            OnMessageReceived = context =>
                            {
                                return(Task.CompletedTask);
                            },
                            OnTokenValidated = context =>
                            {
                                ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                                if (identity != null)
                                {
                                    // Add the access_token as a claim, as we may actually need it
                                    var accessToken = context.SecurityToken as JwtSecurityToken;
                                    if (accessToken != null)
                                    {
                                        if (identity != null)
                                        {
                                            identity.AddClaim(new Claim("access_token", accessToken.RawData));
                                        }
                                    }
                                }

                                return(Task.CompletedTask);
                            }
                        };
                    }
                },
            };

            services.AddAuthentication("Bearer")
            .AddMultiAuthorityAuthentication(schemeRecords);


            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.TryAddTransient <IDefaultHttpClientFactory, DefaultHttpClientFactory>();

            // Build the intermediate service provider then return it
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "GraphQLPlayApiOnly", Version = "v1"
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
            return(services.BuildServiceProvider());
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            services.AddObjectContainer();  // use this vs a static to cache class data.
            services.AddOptions();
            services.Configure <ArbitraryIdentityExtensionGrantOptions>(options => { options.IdentityProvider = "Demo"; });

            services.AddDistributedMemoryCache();
            services.AddGraphQLPlayRollup(this);
            services.AddExtensionGrantsRollup(this);
            services.AddGraphQLDiscoveryTypes();
            services.AddInMemoryDiscoveryHubStore();
            services.AddGraphQLAuthRequiredQuery();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  corsBuilder => corsBuilder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Daffy Duck",
                                  policy => { policy.RequireClaim("client_namespace", "Daffy Duck"); });
            });

            //  var scheme = Configuration["authValidation:scheme"];
            var schemes = Configuration
                          .GetSection("authValidation:schemes")
                          .Get <List <string> >();

            var section       = Configuration.GetSection("InMemoryOAuth2ConfigurationStore:oauth2");
            var oauth2Section = new Oauth2Section();

            section.Bind(oauth2Section);

            var schemeRecords = SchemeRecords(oauth2Section, schemes);

            services.AddAuthentication("Bearer")
            .AddMultiAuthorityAuthentication(schemeRecords);

            services.AddHttpContextAccessor();
            services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.TryAddTransient <IDefaultHttpClientFactory, DefaultHttpClientFactory>();

            // Build the intermediate service provider then return it
            services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc("v1", new Info {
                    Title = "GraphQLPlayTokenExchangeOnlyApp", Version = "v1"
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                config.IncludeXmlComments(xmlPath);
                config.OperationFilter <MultiAuthorityOperationFilter>();
            });
            services.AddInMemoryAppIdentityConfiguration(new AppIdentityConfigurationModel()
            {
                MaxAppIdLength     = Guid.NewGuid().ToString().Length * 2,
                MaxMachineIdLength = Guid.NewGuid().ToString().Length * 2,
                MaxSubjectLength   = Guid.NewGuid().ToString().Length * 2
            });
            return(services.BuildServiceProvider());
        }