コード例 #1
0
 public WebHooksController(IOptions <FacebookOptions> fbOptions, IOptions <MailOptions> mailOptions,
                           ILogger <WebHooksController> logger)
 {
     _fbOptions   = fbOptions.Value;
     _mailOptions = mailOptions.Value;
     _log         = logger;
 }
コード例 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            FacebookOptions fso = new FacebookOptions();

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();
            services.AddAuthentication().AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId     = Configuration["Authentication:Facebook:AppId"];     //-- добавить значение в секреты
                facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; //-- добавить значение в секреты
            });
            services.ConfigureApplicationCookie(identityOptionsCookies =>
            {
                identityOptionsCookies.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });


            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc();
        }
コード例 #3
0
        public TenantMiddleware(
            RequestDelegate next,
            IAuthenticationSchemeProvider oauthProvider,
            IMemoryCache memoryCache,
            IdentityServerOptions identityServerOptions,
            //JwtBearerOptions jwtBearerOptions,
            IOptionsMonitor <MicrosoftAccountOptions> microsoftOptions,
            IOptionsMonitor <GoogleOptions> googleOptions,
            IOptionsMonitor <FacebookOptions> facebookOptions,
            IOptionsMonitor <GitHubAuthenticationOptions> githubOptions,
            IOptionsMonitor <QQAuthenticationOptions> qqOptions,
            IOptionsMonitor <WeiboAuthenticationOptions> weiboOptions,
            IOptionsMonitor <WeixinAuthenticationOptions> weixinOptions

            )
        {
            _next                  = next;
            _oauthProvider         = oauthProvider;
            _memoryCache           = memoryCache;
            _identityServerOptions = identityServerOptions;
            //_jwtBearerOptions = jwtBearerOptions;
            _microsoftOptions = microsoftOptions.Get(MicrosoftAccountDefaults.AuthenticationScheme);
            _googleOptions    = googleOptions.Get(GoogleDefaults.AuthenticationScheme);
            _facebookOptions  = facebookOptions.Get(FacebookDefaults.AuthenticationScheme);
            _githubOptions    = githubOptions.Get(GitHubAuthenticationDefaults.AuthenticationScheme);
            _qqOptions        = qqOptions.Get(QQAuthenticationDefaults.AuthenticationScheme);
            _weiboOptions     = weiboOptions.Get(WeiboAuthenticationDefaults.AuthenticationScheme);
            _weixinOptions    = weixinOptions.Get(WeixinAuthenticationDefaults.AuthenticationScheme);
        }
コード例 #4
0
ファイル: Startup.cs プロジェクト: tarasmychats/Merp
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            var facebookOptions = new FacebookOptions()
            {
                AppId     = Configuration["Authentication:Facebook:AppId"],
                AppSecret = Configuration["Authentication:Facebook:AppSecret"]
            };

            facebookOptions.Fields.Add("email");
            facebookOptions.Fields.Add("first_name");
            facebookOptions.Fields.Add("last_name");
            app.UseFacebookAuthentication(facebookOptions);

            var googleOptions = new GoogleOptions()
            {
                ClientId     = Configuration["Authentication:Google:ClientId"],
                ClientSecret = Configuration["Authentication:Google:ClientSecret"],
                Scope        = { "email", "openid" }
            };

            app.UseGoogleAuthentication(googleOptions);

            var microsoftAccountOptions = new MicrosoftAccountOptions()
            {
                ClientId     = Configuration["Authentication:MicrosoftAccount:ClientId"],
                ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
            };

            app.UseMicrosoftAccountAuthentication(microsoftAccountOptions);

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

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #5
0
 public ExternalLoginService(IOptions <OpenIdOptions> openIdOptionsAccessor, ICacheService cacheService,
                             IOptions <GoogleOptions> googleOptionsAccessor, IOptions <FacebookOptions> facebookOptionsAccessor)
 {
     _cacheService    = cacheService;
     _openIdOptions   = openIdOptionsAccessor.Value;
     _googleOptions   = googleOptionsAccessor.Value;
     _facebookOptions = facebookOptionsAccessor.Value;
 }
コード例 #6
0
 public FacebookController(GiveOrTakeContext dbContext,
                           IOptions <FacebookOptions> facebookOptions,
                           LoginHelper loginHelper)
 {
     this.facebookOptions = facebookOptions.Value;
     this.loginHelper     = loginHelper;
     this.dbContext       = dbContext;
 }
コード例 #7
0
 public static FacebookOptionsLite Create(FacebookOptions opts)
 {
     return(new FacebookOptionsLite
     {
         AppId = opts.AppId,
         AppSecret = opts.AppSecret
     });
 }
コード例 #8
0
 public WebHooksController(IOptions <FacebookOptions> fbOptions, IOptions <MailOptions> mailOptions,
                           ILogger <WebHooksController> logger, IRepository <FacebookAdsLog> facebookAdsLogRepo, IRepository <FacebookAdsFormData> facebookAdsFormDataRepo)
 {
     _fbOptions               = fbOptions.Value;
     _mailOptions             = mailOptions.Value;
     _log                     = logger;
     _facebookAdsLogRepo      = facebookAdsLogRepo;
     _facebookAdsFormDataRepo = facebookAdsFormDataRepo;
 }
コード例 #9
0
 public AuthController(UserManager <AppUser> userManager, SignInManager <AppUser> signInManager, IJwtService jwtService, IOptions <JwtIssuerOptions> jwtOptions, IOptions <FacebookOptions> facebookOptions, ILogger <AuthController> logger)
 {
     _userManager     = userManager;
     _signInManager   = signInManager;
     _jwtService      = jwtService;
     _jwtOptions      = jwtOptions.Value;
     _facebookOptions = facebookOptions.Value;
     _logger          = logger;
 }
コード例 #10
0
        public static string GetFacebookOption(RestCommand command, int organizationID)
        {
            FacebookOption facebookOption = FacebookOptions.GetFacebookOption(command.LoginUser, organizationID);

            if (facebookOption.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(facebookOption.GetXml("FacebookOption", true));
        }
コード例 #11
0
        /// <summary>
        /// Authenticate users using Facebook.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
        /// <param name="configureOptions">Configures the options.</param>
        /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
        public static IApplicationBuilder UseFacebookAuthentication([NotNull] this IApplicationBuilder app, Action <FacebookOptions> configureOptions)
        {
            var options = new FacebookOptions();

            if (configureOptions != null)
            {
                configureOptions(options);
            }
            return(app.UseFacebookAuthentication(options));
        }
コード例 #12
0
        public async Task AddAsync_should_add_facebook_handler()
        {
            var eventCalled = false;

            Task onCreatingTicket(OAuthCreatingTicketContext context)
            {
                eventCalled = true;
                return(Task.CompletedTask);
            }

            var provider = CreateServiceProvider(options =>
            {
                options.AddFacebook(configure =>
                {
                    configure.Events.OnCreatingTicket = onCreatingTicket;
                });
            });

            var sut = provider.GetRequiredService <AuthenticationSchemeProviderWrapper>();

            Assert.Contains(typeof(FacebookHandler), sut.GetManagedHandlerTypes());

            var facebookOptions = new FacebookOptions
            {
                AppId     = "test",
                AppSecret = "test"
            };

            var scheme     = Guid.NewGuid().ToString();
            var definition = new TSchemeDefinition
            {
                Scheme      = scheme,
                DisplayName = "test",
                HandlerType = typeof(FacebookHandler),
                Options     = facebookOptions
            };

            await sut.AddAsync(definition);

            var state = await VerifyAddedAsync <FacebookOptions>(scheme, provider);

            var httpContext = new Mock <HttpContext>().Object;

            state.options.Events.OnCreatingTicket(new OAuthCreatingTicketContext(
                                                      new ClaimsPrincipal(),
                                                      new AuthenticationProperties(),
                                                      httpContext,
                                                      state.scheme as AuthenticationScheme,
                                                      state.options as FacebookOptions,
                                                      new HttpClient(),
                                                      OAuthTokenResponse.Failed(new Exception()),
                                                      JsonDocument.Parse("{ \"name\": \"test\"}").RootElement));

            Assert.True(eventCalled);
        }
コード例 #13
0
 public MultiTenantFacebookOptionsResolver(
     FacebookOptions originalOptions,
     ISiteResolver siteResolver,
     ISiteRepository siteRepository,
     MultiTenantOptions multiTenantOptions)
 {
     this.originalOptions    = originalOptions;
     this.siteResolver       = siteResolver;
     this.multiTenantOptions = multiTenantOptions;
     siteRepo = siteRepository;
 }
コード例 #14
0
        private FacebookOptions GetFacebookOptions(IConfigurationRoot configuration)
        {
            var options = new FacebookOptions();

            //options.AppId = Configuration["FacebookAppId"];
            //options.AppSecret = Configuration["FacebookAppSecret"];
            options.AppId     = "1772882172935332";
            options.AppSecret = "d64960e5f0d1f0dc58b670057d97b80c";
            options.Scope.Add("email");

            return(options);
        }
コード例 #15
0
        private static FacebookOptions CreateFacebookAuthOptions(IConfiguration configuration)
        {
            var options = new FacebookOptions
            {
                AppId     = configuration["Authentication:Facebook:AppId"],
                AppSecret = configuration["Authentication:Facebook:AppSecret"]
            };

            options.Scope.Add("email");
            options.Scope.Add("public_profile");

            return(options);
        }
コード例 #16
0
 public OAuthRepository(
     ILogger <SessionRepository> logger,
     SignInManager <ApplicationUser> signInManager,
     UserManager <ApplicationUser> userManager,
     IOptionsMonitor <GoogleOptions> googleOptionsMonitor,
     IOptionsMonitor <FacebookOptions> facebookOptionsMonitor)
 {
     logger_          = logger;
     signInManager_   = signInManager;
     userManager_     = userManager;
     googleOptions_   = googleOptionsMonitor.Get(GoogleDefaults.AuthenticationScheme);
     facebookOptions_ = facebookOptionsMonitor.Get(FacebookDefaults.AuthenticationScheme);
 }
        public static IApplicationBuilder UseExternalAuth(this IApplicationBuilder application, IConfigurationRoot configuration)
        {
            var externalCookieScheme = application.ApplicationServices.GetRequiredService <IOptions <IdentityOptions> >().Value.Cookies.ExternalCookieAuthenticationScheme;
            // or use
            var facebookOptions = new FacebookOptions
            {
                AuthenticationScheme = "facebook",
                DisplayName          = "Facebook",
                SignInScheme         = externalCookieScheme,
                AppId      = configuration["Auth:Facebook:AppId"],
                AppSecret  = configuration["Auth:Facebook:AppSecret"],
                SaveTokens = true,
                Events     = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var payload = await GetUserInfo(context);

                        JsonKeyClaim claims = new JsonKeyClaim(context.Identity, payload, context.Options.ClaimsIssuer);
                        claims.TryAddClaimByJsonKey("urn:facebook:photo", "picture");
                    }
                }
            };

            var gooleOptions = new GoogleOptions
            {
                AuthenticationScheme = "google",
                DisplayName          = "Google",
                SignInScheme         = externalCookieScheme,
                ClientId             = configuration["Auth:Google:ClientId"],
                ClientSecret         = configuration["Auth:Google:ClientSecret"],
                SaveTokens           = true,
                Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var payload = await GetUserInfo(context);

                        JsonKeyClaim claims = new JsonKeyClaim(context.Identity, payload, context.Options.ClaimsIssuer);
                        claims.TryAddClaimByJsonSubKey("urn:google:photo", "image", "url");
                        claims.TryAddClaimByJsonKey(ClaimTypes.Locality, "language");
                        claims.TryAddClaimByJsonSubKey("urn:google:location", "location", "name");
                    }
                }
            };

            return(application
                   // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
                   .UseFacebookAuthentication(facebookOptions)
                   .UseGoogleAuthentication(gooleOptions));
        }
コード例 #18
0
        public TenantMiddleware(
            RequestDelegate next,
            TenantService tenantService,
            IAuthenticationSchemeProvider oauthProvider,
            IMemoryCache memoryCache,
            IdentityServerOptions identityServerOptions,

            IOptionsMonitor <AmazonAuthenticationOptions> amazonOptions,
            IOptionsMonitor <FacebookOptions> facebookOptions,
            IOptionsMonitor <GitHubOptions> githubOptions,
            IOptionsMonitor <GitterAuthenticationOptions> gitterOptions,
            IOptionsMonitor <GoogleOptions> googleOptions,
            IOptionsMonitor <InstagramAuthenticationOptions> instagramOptions,
            IOptionsMonitor <LinkedInAuthenticationOptions> linkedinOptions,
            IOptionsMonitor <MicrosoftAccountOptions> microsoftOptions,
            IOptionsMonitor <PaypalAuthenticationOptions> paypalOptions,
            IOptionsMonitor <QQOptions> qqOptions,
            IOptionsMonitor <RedditAuthenticationOptions> redditOptions,
            IOptionsMonitor <SalesforceAuthenticationOptions> salesforceOptions,
            IOptionsMonitor <TwitterOptions> twitterOptions,
            IOptionsMonitor <VisualStudioAuthenticationOptions> visualstudioOptions,
            IOptionsMonitor <WeiboOptions> weiboOptions,
            IOptionsMonitor <WeixinOptions> weixinOptions,
            IOptionsMonitor <WordPressAuthenticationOptions> wordpressOptions
            )
        {
            _next                  = next;
            _tenantService         = tenantService;
            _oauthProvider         = oauthProvider;
            _memoryCache           = memoryCache;
            _identityServerOptions = identityServerOptions;

            _amazonOptions       = amazonOptions.CurrentValue;
            _facebookOptions     = facebookOptions.CurrentValue;
            _githubOptions       = githubOptions.CurrentValue;
            _gitterOptions       = gitterOptions.CurrentValue;
            _googleOptions       = googleOptions.CurrentValue;
            _instagramOptions    = instagramOptions.CurrentValue;
            _linkedinOptions     = linkedinOptions.CurrentValue;
            _microsoftOptions    = microsoftOptions.CurrentValue;
            _paypalOptions       = paypalOptions.CurrentValue;
            _qqOptions           = qqOptions.CurrentValue;
            _redditOptions       = redditOptions.CurrentValue;
            _salesforceOptions   = salesforceOptions.CurrentValue;
            _twitterOptions      = twitterOptions.CurrentValue;
            _visualstudioOptions = visualstudioOptions.CurrentValue;
            _weiboOptions        = weiboOptions.CurrentValue;
            _weixinOptions       = weixinOptions.CurrentValue;
            _wordpressOptions    = wordpressOptions.CurrentValue;
        }
コード例 #19
0
        private static Action <IApplicationBuilder> FacebookAuthentication(IConfiguration configuration)
        {
            var options = new FacebookOptions
            {
                AppId     = configuration.AuthenticationFacebookAppId(),
                AppSecret = configuration.AuthenticationFacebookAppSecret(),
                BackchannelHttpHandler  = new HttpClientHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email",
            };

            options.Scope.Add("email");

            return(app => app.UseFacebookAuthentication(options));
        }
コード例 #20
0
        /// <summary>
        /// Adds the <see cref="FacebookMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Facebook authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="configureOptions">An action delegate to configure the provided <see cref="FacebookOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app, Action <FacebookOptions> configureOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var options = new FacebookOptions();

            if (configureOptions != null)
            {
                configureOptions(options);
            }
            return(app.UseFacebookAuthentication(options));
        }
コード例 #21
0
        /// <summary>
        /// Add Facebook authentication to the application.
        /// </summary>
        /// <param name="app">Current application request pipeline.</param>
        /// <param name="configuration">The configuration object from which to get <c>AppId</c> and <c>AppSecret</c>.</param>
        public static void AddFacebookAuthentication(this IApplicationBuilder app, IConfigurationRoot configuration)
        {
            string facebookAppId     = configuration["Authentication:Facebook:AppId"];
            string facebookAppSecret = configuration["Authentication:Facebook:AppSecret"];
            var    facebookOptions   = new FacebookOptions
            {
                AppId     = facebookAppId,
                AppSecret = facebookAppSecret
            };

            if (facebookOptions.IsConfigurationValid())
            {
                app.UseFacebookAuthentication(facebookOptions);
            }
        }
コード例 #22
0
        public static string GetFacebookOptions(RestCommand command)
        {
            FacebookOptions facebookOptions = new FacebookOptions(command.LoginUser);

            facebookOptions.LoadByOrganizationID(command.Organization.OrganizationID);

            if (command.Format == RestFormat.XML)
            {
                return(facebookOptions.GetXml("FacebookOptions", "FacebookOption", true, command.Filters));
            }
            else
            {
                throw new RestException(HttpStatusCode.BadRequest, "Invalid data format");
            }
        }
コード例 #23
0
        public static IApplicationBuilder UseMultiTenantFacebookAuthentication(
            this IApplicationBuilder app,
            Action <FacebookOptions> configureOptions)
        {
            //https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Authentication.Facebook/FacebookOptions.cs
            // https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNet.Authentication.OAuth/OAuthOptions.cs

            var options = new FacebookOptions();

            if (configureOptions != null)
            {
                configureOptions(options);
            }

            return(app.UseMiddleware <MultiTenantFacebookMiddleware>(options));
        }
コード例 #24
0
 public MultiTenantFacebookOptionsResolver(
     FacebookOptions originalOptions,
     //ISiteResolver siteResolver,
     //IHttpContextAccessor contextAccessor,
     //ITenantResolver<SiteSettings> siteResolver,
     ISiteSettings currentSite,
     //ISiteRepository siteRepository,
     MultiTenantOptions multiTenantOptions)
 {
     this.originalOptions = originalOptions;
     //this.siteResolver = siteResolver;
     //this.contextAccessor = contextAccessor;
     this.multiTenantOptions = multiTenantOptions;
     //siteRepo = siteRepository;
     site = currentSite;
 }
コード例 #25
0
        public BaseTests()
        {
            FacebookOptions = new FacebookOptions()
            {
                AppId      = "",
                AppSecret  = "",
                SaveTokens = true,
            };

            FacebookOptions.Scope.Add("email");
            FacebookOptions.Scope.Add("user_birthday");
            FacebookOptions.Scope.Add("user_gender");
            FacebookOptions.Scope.Add("user_posts");
            FacebookOptions.Scope.Add("manage_pages");
            FacebookOptions.Scope.Add("user_photos ");
            FacebookOptions.Scope.Add("publish_pages");
        }
コード例 #26
0
        public static FacebookOptions FacebookOptions(string appId, string appSecret)
        {
            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException($"{nameof(appId)} is null or empty");
            }

            if (string.IsNullOrEmpty(appSecret))
            {
                throw new ArgumentNullException($"{nameof(appSecret)} is null or empty");
            }

            FacebookOptions options = new FacebookOptions
            {
                AppId      = appId,
                AppSecret  = appSecret,
                SaveTokens = true,
                Scope      = { "email", "user_friends" },
                Events     = new OAuthEvents
                {
                    OnCreatingTicket = ctx =>
                    {
                        // Get a Facebook specific claim (This will be added to the Name claim
                        string facebookFirstname = ctx.User.GetValue("first_name").ToObject <string>();

                        ctx.Identity.AddClaim(new Claim("access_token", ctx.AccessToken));
                        ctx.Identity.AddClaim(new Claim("refresh_token", ctx.AccessToken));
                        ctx.Identity.AddClaim(new Claim("ExpiresIn", ctx.ExpiresIn.Value.Seconds.ToString()));
                        ctx.Identity.AddClaim(new Claim("FBFirstname", facebookFirstname)); // Add custom claim to the identity

                        return(Task.FromResult(0));
                    },
                    OnRemoteFailure = ctx =>
                    {
                        // Handle remote errors

                        return(Task.FromResult(0));
                    }
                }
            };

            return(options);
        }
コード例 #27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            FacebookOptions facebookOptions = new FacebookOptions();

            facebookOptions.Scope.Add("email");
            facebookOptions.Scope.Add("public_profile");
            facebookOptions.AppId     = Configuration["Authentication:Facebook:AppId"];
            facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            facebookOptions.ClientId  = Configuration["Authentication:Facebook:AppId"];
            //app.UseFacebookAuthentication(facebookOptions);
            app.UseIdentity().UseFacebookAuthentication(facebookOptions);

            app.SeedData();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #28
0
        public void Configure(string name, FacebookOptions options)
        {
            if (!string.Equals(name, FacebookDefaults.AuthenticationScheme, StringComparison.Ordinal))
            {
                return;
            }

            if (!ValidSettings())
            {
                return;
            }

            options.AppId     = _platoFacebookOptions.AppId;
            options.AppSecret = _platoFacebookOptions.AppSecret;

            if (_platoFacebookOptions.CallbackPath.HasValue)
            {
                options.CallbackPath = _platoFacebookOptions.CallbackPath;
            }
        }
コード例 #29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }



            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

            FacebookOptions FbOptions = new FacebookOptions();

            FbOptions.AppId     = Configuration["Authentication:Facebook:AppId"];
            FbOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            FbOptions.Scope.Add("email");
            FbOptions.Scope.Add("public_profile");
            FbOptions.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name";
            app.UseFacebookAuthentication(FbOptions);


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #30
0
        public void Configure(string name, FacebookOptions options)
        {
            // Ignore OpenID Connect client handler instances that don't correspond to the instance managed by the OpenID module.
            if (!String.Equals(name, FacebookDefaults.AuthenticationScheme))
            {
                return;
            }

            var coreSettings = GetFacebookCoreSettingsAsync().GetAwaiter().GetResult();

            if (coreSettings == null)
            {
                return;
            }

            var loginSettings = GetFacebookLoginSettingsAsync().GetAwaiter().GetResult();

            if (loginSettings == null)
            {
                return;
            }

            options.AppId = coreSettings.AppId;

            try
            {
                options.AppSecret = _dataProtectionProvider.CreateProtector(FacebookConstants.Features.Core).Unprotect(coreSettings.AppSecret);
            }
            catch
            {
                _logger.LogError("The Facebook secret key could not be decrypted. It may have been encrypted using a different key.");
            }

            if (loginSettings.CallbackPath.HasValue)
            {
                options.CallbackPath = loginSettings.CallbackPath;
            }

            options.SaveTokens = loginSettings.SaveTokens;
        }