Пример #1
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            // app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            var linkedinoptions = new LinkedInAuthenticationOptions
            {
                ClientId     = "77oba6ddrqi37w",
                ClientSecret = "vb7paAa7jO0AwFzx",
                Provider     = new LinkedInAuthenticationProvider()
                {
                    //OnAuthenticated = (context) =>
                    //{
                    //}
                }
            };

            app.UseLinkedInAuthentication(linkedinoptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Пример #2
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            //allow all cross site requests, very important do not remove
            app.UseCors(CorsOptions.AllowAll); //seriosly don't FFFF with this

            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp         = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers


            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
            var linkedInOptions = new LinkedInAuthenticationOptions()
            {
                ClientId           = OAuthProvidersConfiguration.LinkedIn_OAuth_ClientID,
                ClientSecret       = OAuthProvidersConfiguration.LinkedIn_OAuth_ClientSecret,
                AuthenticationType = DefaultAuthenticationTypes.ExternalBearer
            };

            app.UseLinkedInAuthentication(linkedInOptions);
        }
Пример #3
0
        public static IApplicationBuilder UseLinkedInAuthentication(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action <LinkedInAuthenticationOptions> configuration)
        {
            var options = new LinkedInAuthenticationOptions();

            configuration(options);

            return(app.UseLinkedInAuthentication(options));
        }
Пример #4
0
        public override void ConfigureMiddleware(IAppBuilder appBuilder,
                                                 Microsoft.WindowsAzure.Mobile.Service.ServiceSettingsDictionary settings)
        {
            LinkedInAuthenticationOptions options = new LinkedInAuthenticationOptions
            {
                ClientId           = settings["LinkedInClientId"],
                ClientSecret       = settings["LinkedInClientSecret"],
                AuthenticationType = this.Name,
                Provider           = new LinkedInAuthenticationProvider()
            };

            appBuilder.UseLinkedInAuthentication(options);
        }
Пример #5
0
        /// <summary>
        /// Add LinkedIn authentication to the application.
        /// </summary>
        /// <param name="app">Current application request pipeline.</param>
        /// <param name="configuration">The configuration object from which to get <c>ClientId</c> and <c>ClientSecret</c>.</param>
        public static void AddLinkedInAuthentication(this IApplicationBuilder app, IConfigurationRoot configuration)
        {
            var linkedInAuthenticationOptions = new LinkedInAuthenticationOptions
            {
                ClientId     = configuration["Authentication:LinkedIn:ClientId"],
                ClientSecret = configuration["Authentication:LinkedIn:ClientSecret"]
            };

            if (linkedInAuthenticationOptions.IsConfigurationValid())
            {
                app.UseLinkedInAuthentication(linkedInAuthenticationOptions);
            }
        }
        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;
        }
Пример #7
0
        /// <summary>
        /// Adds the <see cref="LinkedInAuthenticationMiddleware"/> middleware to the specified
        /// <see cref="IApplicationBuilder"/>, which enables LinkedIn authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">A <see cref="LinkedInAuthenticationOptions"/> that specifies options for the middleware.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseLinkedInAuthentication(
            [NotNull] this IApplicationBuilder app,
            [NotNull] LinkedInAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <LinkedInAuthenticationMiddleware>(Options.Create(options)));
        }
Пример #8
0
        /// <summary>
        /// Adds the <see cref="LinkedInAuthenticationMiddleware"/> middleware to the specified
        /// <see cref="IApplicationBuilder"/>, which enables LinkedIn authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="configuration">An action delegate to configure the provided <see cref="LinkedInAuthenticationOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseLinkedInAuthentication(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action <LinkedInAuthenticationOptions> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var options = new LinkedInAuthenticationOptions();

            configuration(options);

            return(app.UseMiddleware <LinkedInAuthenticationMiddleware>(Options.Create(options)));
        }
Пример #9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(IlevusIdentityContext.Create);
            app.CreatePerOwinContext <IlevusUserManager>(IlevusUserManager.Create);
            app.CreatePerOwinContext <IlevusRoleManager>(IlevusRoleManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthAuthzOpts = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/api/Token"),
                Provider                  = new IlevusOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/User/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp         = true
            };
            OAuthBearerOpts = new OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerAuthentication(OAuthBearerOpts);
            app.UseOAuthBearerTokens(OAuthAuthzOpts);

            // Code for third party logins
            linkedinAuthOptions = new LinkedInAuthenticationOptions
            {
                ClientId     = ConfigurationManager.AppSettings["LinkedinClient"],
                ClientSecret = ConfigurationManager.AppSettings["LinkedinSecret"]
            };

            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FacebookClient"],
                AppSecret = ConfigurationManager.AppSettings["FacebookSecret"]
            };
        }
Пример #10
0
        public virtual void ConfigureExternalIdentityProvider(IAppBuilder owinApp, string signInType)
        {
            if (AppEnvironment.HasConfig("LinkedInClientId") && AppEnvironment.HasConfig("LinkedInSecret"))
            {
                string linkedInClientId = AppEnvironment.GetConfig <string>("LinkedInClientId");
                string linkedInSecret   = AppEnvironment.GetConfig <string>("LinkedInSecret");

                Task LinkedInOnAuthenticated(LinkedInAuthenticatedContext context)
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken));

                    foreach (KeyValuePair <string, JToken> claim in context.User)
                    {
                        string claimType  = $"{claim.Key}";
                        string claimValue = claim.Value.ToString();

                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                        }
                    }

                    return(Task.CompletedTask);
                }

                LinkedInAuthenticationOptions linkedInAuthenticationOptions = new LinkedInAuthenticationOptions
                {
                    AuthenticationType         = "LinkedIn",
                    SignInAsAuthenticationType = signInType,
                    ClientId     = linkedInClientId,
                    ClientSecret = linkedInSecret,
                    Provider     = new LinkedInAuthenticationProvider
                    {
                        OnAuthenticated = LinkedInOnAuthenticated
                    }
                };

                owinApp.UseLinkedInAuthentication(linkedInAuthenticationOptions);
            }
        }
Пример #11
0
        public static LinkedInAuthenticationOptions LinkedInOptions(string clientId, string clientSecret)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException($"{nameof(clientId)} is null or empty");
            }

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

            LinkedInAuthenticationOptions options = new LinkedInAuthenticationOptions
            {
                ClientId     = clientId,
                ClientSecret = clientSecret,
                SaveTokens   = true,
                Events       = new OAuthEvents
                {
                    OnCreatingTicket = ctx =>
                    {
                        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()));

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

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

            return(options);
        }
Пример #12
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            app.UseCustomJwtBearerToken();

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath          = new PathString(CookieLoginPath)
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            LinkedInAuthenticationOptions inOptions = new LinkedInAuthenticationOptions();

            inOptions.ClientId     = LinkedInClientId;
            inOptions.ClientSecret = LinkedInClientSecrete;
            inOptions.CallbackPath = new PathString(LinkedInCallbackPath);
            app.UseLinkedInAuthentication(inOptions);
        }
Пример #13
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/api/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            var linkedinOptions = new LinkedInAuthenticationOptions()
            {
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
                ClientId     = ConfigurationManager.AppSettings["LinkedInAPIKey"].ToString(),
                ClientSecret = ConfigurationManager.AppSettings["LinkedInAPISecret"].ToString(),
                Scope        = { "r_basicprofile", "r_emailaddress" },
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedIn_AccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseLinkedInAuthentication(linkedinOptions);

            var facebookOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FacebookAPIKey"].ToString(),
                AppSecret = ConfigurationManager.AppSettings["FacebookAPISecret"].ToString(),
                BackchannelHttpHandler  = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email",
                Scope    = { "email" },
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                }
            };

            app.UseFacebookAuthentication(facebookOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GoogleAPIKey"].ToString(),
                ClientSecret = ConfigurationManager.AppSettings["GoogleAPISecret"].ToString()
            });
        }
Пример #14
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "000000004C14CB77",
            //    clientSecret: "jDpRcoE2B6c2QyXowqf-mQSs6jhyEJg6");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");
            var facebook = new FacebookAuthenticationOptions();

            facebook.AppId     = "799303593470744";
            facebook.AppSecret = "778c1b6233044d2ff483648f6f6f081f";

            facebook.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                        }
                    }
                }
            };
            facebook.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(facebook);



            var googlePlusOptions = new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = "158077854351-477nr7dcbfhf7h3mdb0lrmdbdk3h92of.apps.googleusercontent.com",
                ClientSecret = "KVEiZakJErf9-LuUwkGTZzMy",
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async googleContext =>
                    {
                        googleContext.Identity.AddClaim(new Claim("urn:tokens:googleplus:accesstoken", googleContext.AccessToken));
                        foreach (var claim in googleContext.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!googleContext.Identity.HasClaim(claimType, claimValue))
                            {
                                googleContext.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                },
            };

            app.UseGoogleAuthentication(googlePlusOptions);



            var linkedin = new LinkedInAuthenticationOptions();

            linkedin.ClientId     = "775uyaqv9v2zhx";
            linkedin.ClientSecret = "xPguLm68a67fFu5Z";
            linkedin.Provider     = new LinkedInAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("urn:linkedin:accesstoken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:linkedin:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                        }
                    }
                }
            };
            linkedin.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseLinkedInAuthentication(linkedin);
            //app.UseLinkedInAuthentication("775uyaqv9v2zhx", "xPguLm68a67fFu5Z");
        }
Пример #15
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            //app.UseLinkedInAuthentication(
            //    clientId: "77pah7ccc33mwt",
            //    clientSecret: "ox4SkRtigJLBAtpv");

            var linkedInOptions = new LinkedInAuthenticationOptions();

            linkedInOptions.ClientId     = "77pah7ccc33mwt";
            linkedInOptions.ClientSecret = "ox4SkRtigJLBAtpv";


            linkedInOptions.Scope.Add("r_basicprofile");

            linkedInOptions.Provider = new LinkedInAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedIn_AccessToken", context.AccessToken));
                }
            };

            linkedInOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;

            app.UseLinkedInAuthentication(linkedInOptions);
        }
Пример #16
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                LogoutPath         = new PathString("/Account/Logout"),
                ExpireTimeSpan     = TimeSpan.FromMinutes(5.0),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(new TwitterAuthenticationExtensions()
            //{ consumerKey: "MmB1lal6cGkHUzcXo0fqhhOwD",
            //consumerSecret: "	sJPh7us5fAR7QsjZgz3h6gUC107N4WL7LYBrCugCrDbHffekIX",
            // BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
            //    {

            //      "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
            //      "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
            //      "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary CA - G5
            //      "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
            //      "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
            //      "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
            //      "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
            //      "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
            //    })
            //});

            //var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
            //{
            //    AppId = "364846563994378",
            //    AppSecret = "f26a0cabce9d9272734be06847747553",
            //    UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            //    BackchannelHttpHandler = new FacebookBackChannelHandler(),
            //    CallbackPath = new PathString("/oauth-redirect/facebook")
            //};
            //facebookOptions.Scope.Add("email");
            //app.UseFacebookAuthentication(facebookOptions);

            //var gProvider = new GoogleOAuth2AuthenticationProvider { OnAuthenticated = context => Task.FromResult(0) };
            //var gOptions = new GoogleOAuth2AuthenticationOptions { Provider = gProvider, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie };
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "514477754818-a761lbmu5c25jvmp7baajmi3die5a41o.apps.googleusercontent.com",
                ClientSecret = "t5c7KbIul097s0JQH2PGZLOm",
                CallbackPath = new PathString("/signin-google")
            });
            var linkedInOptions = new LinkedInAuthenticationOptions();

            linkedInOptions.ClientId     = "86lcyi8hwtnxkg";
            linkedInOptions.ClientSecret = "1Hq8DRQNEhF56imD";

            linkedInOptions.Scope.Add("r_emailaddress");

            linkedInOptions.Provider = new LinkedInAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedIn_AccessToken", context.AccessToken));
                }
            };

            linkedInOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;

            app.UseLinkedInAuthentication(linkedInOptions);
        }
Пример #17
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                ExpireTimeSpan    = TimeSpan.FromHours(24),
                SlidingExpiration = true
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            var linkedinOptions = new LinkedInAuthenticationOptions
            {
                ClientId     = ConfigurationHelper.LinkedInClientId,
                ClientSecret = ConfigurationHelper.LinkedInClientKey,
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        foreach (var x in context.User)
                        {
                            var    claimType  = string.Format("urn:linkedin:{0}", x.Key);
                            string claimValue = x.Value.ToString();
                            if (!context.Identity.HasClaim(claim => claim.Value == claimValue))
                            {
                                context.Identity.AddClaim(new Claim(claimType, claimValue));
                            }
                        }

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

            List <string> profileFieldsToGet = new List <string>()
            {
                "r_basicprofile",
                "vanityName"
            };

            foreach (var field in profileFieldsToGet)
            {
                linkedinOptions.ProfileFields.Add(field);
            }

            app.UseLinkedInAuthentication(linkedinOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Пример #18
0
 public static IApplicationBuilder UseLinkedInAuthentication(
     [NotNull] this IApplicationBuilder app,
     [NotNull] LinkedInAuthenticationOptions options)
 {
     return(app.UseMiddleware <LinkedInAuthenticationMiddleware>(options));
 }
Пример #19
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "891861927596279",
            //   appSecret: "aad6cb03fd28fef2b42d68fbb1d32eb6");

            //app.SetDefaultSignInAsAuthenticationType("ExternalCookie");
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = "ExternalCookie",
            //    AuthenticationMode = AuthenticationMode.Passive,
            //});
            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId     = "881522805296858",
                AppSecret = "2f684709a9941475e25bc3657754241a",
                Scope     = { "email" },
                BackchannelHttpHandler  = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                }
            });
            //app.UseLinkedInAuthentication("75pbqe8ynp8ror", "s75PeQB8PjHIOE05");
            var options = new LinkedInAuthenticationOptions
            {
                ClientId     = "75wiw6rws21340",
                ClientSecret = "0xRiBDQmiYrvt1Hp",
            };

            app.UseLinkedInAuthentication(options);
            //var facebookOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "881522805296858",
            //    AppSecret = "2f684709a9941475e25bc3657754241a",
            //    BackchannelHttpHandler = new FacebookBackChannelHandler(),
            //    UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location"
            //};
            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "148671946656-fh3qu8mt23bbjquqm9g6vaobem0ph85d.apps.googleusercontent.com",
            //    ClientSecret = "opA9C1Q7z7ws9q-u1E8QOFK6"
            //});
        }
Пример #20
0
        //This method is inside App_Start/Startup.Auth.cs
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            #region Microsoft

            var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                Provider     = new MicrosoftAccountAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                            }
                        }
                    }
                }
            };
            microsoftAuthenticationOptions.Scope.Add("wl.basic");
            microsoftAuthenticationOptions.Scope.Add("wl.emails");
            microsoftAuthenticationOptions.Scope.Add("wl.birthday");
            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);

            #endregion Microsoft

            #region Twitter
            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwtI"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwtS"],
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                    new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                }),
                Provider = new TwitterAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken));
                        foreach (var claim in context.UserId)
                        {
                            var    claimType  = string.Format("urn:twitter:{0}", claim);
                            string claimValue = claim.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter"));
                            }
                        }
                    }
                }
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region Facebook

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FaceI"],
                AppSecret = ConfigurationManager.AppSettings["FaceS"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }
                    }
                }
            };
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            #endregion Facebook

            #region Google

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GglI"],
                ClientSecret = ConfigurationManager.AppSettings["GglS"],
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                }
            };
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);

            #endregion Google

            #region LinkedIn

            var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkI"],
                ClientSecret = ConfigurationManager.AppSettings["LinkS"],
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:linkedin:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                            }
                        }
                    }
                }
            };
            app.UseLinkedInAuthentication(linkedinAuthenticationOptions);

            #endregion LinkedIn

            #region GitHub

            var gitAuthanticationOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GitI"],
                ClientSecret = ConfigurationManager.AppSettings["GitS"],
                Provider     = new GitHubAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:github:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub"));
                            }
                        }
                    }
                }
            };
            app.UseGitHubAuthentication(gitAuthanticationOptions);

            #endregion GitHub
        }
Пример #21
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "857698632407-2oh1dlmgvkcr3s1t7ogk2r1kvvr2t34v.apps.googleusercontent.com",
                ClientSecret = "EwDEtu5aecpoPO74wQTQNDDy",
                Provider     = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "1050543328368934",
                AppSecret = "78145c119c1d6c64dd64bf129cc3a0c2",
                Provider  = new FacebookAuthProvider()
            };

            facebookAuthOptions.Scope.Add("email");

            app.UseFacebookAuthentication(facebookAuthOptions);

            linkedInAuthOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = "78h6qf8zyp15lg",
                ClientSecret = "I86DaIuxrfqsv3tW",
                Provider     = new LinkedInAuthProvider()
            };
            app.UseLinkedInAuthentication(linkedInAuthOptions);

            twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = "6hiW6eeKKWNx00xBiICcbtVlP",
                ConsumerSecret = "kI5gRkew9tf0l1itwReiFj5L7dnFwWjTRSldh5IsmnAQrNc0Yn",
                Provider       = new TwitterAuthProvider(),
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47",  // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5",  // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",  // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD",  // Symantec Class 3 Secure Server CA - G4
                    "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",  // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B",  // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"   // DigiCert High Assurance EV Root CA
                })
            };
            app.UseTwitterAuthentication(twitterAuthOptions);
        }
Пример #22
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext();

            LinkedInAuthClient linkedInAuthClient = db.LinkedInAuthClients.SingleOrDefault(_linked => _linked.Active);

            if (linkedInAuthClient != null)
            {
                ILinkedInAuthenticationProvider providerLnk = new KaribouAlpha.Authentication.LinkedInAuthenticationProvider();
                LinkedInAuthenticationOptions = new LinkedInAuthenticationOptions()
                {
                    ClientId     = linkedInAuthClient.ClientId,
                    ClientSecret = linkedInAuthClient.ClientSecret,
                    Provider     = providerLnk,
                    CallbackPath = new PathString("/AuthCallBack."),
                    Scope        = { "r_basicprofile", "r_emailaddress" },
                    //BackchannelHttpHandler = new LinkedInBackChannelHandler()
                };
            }
            //http://www.c-sharpcorner.com/article/implementing-oauth2-0-authorization-for-google-in-asp-net/
            //https://developers.google.com/actions/identity/oauth2-code-flow

            GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active);

            if (googleClient != null)
            {
                GoogleAuthProvider gProvider = new GoogleAuthProvider();
                googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = googleClient.ClientId,
                    ClientSecret = googleClient.ClientSecret,
                    Provider     = gProvider
                };
            }

            KaribouAlpha.Models.FaceBookClient clientFb = db.FaceBookClients.SingleOrDefault(_fb => _fb.Active);
            if (clientFb != null)
            {
                var fbProvider          = new FacebookAuthProvider();
                var facebookAuthOptions = new FacebookAuthenticationOptions()
                {
                    AppId     = clientFb.AppId,
                    AppSecret = clientFb.AppSecret,
                    Provider  = fbProvider,
                };
                app.UseFacebookAuthentication(facebookAuthOptions);
            }
        }
Пример #23
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(MmmContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, User>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");
            #region LinkedIn

            var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkedinClientId"],
                ClientSecret = ConfigurationManager.AppSettings["LinkedinClientSecretKey"],
            };

            //linkedinAuthenticationOptions.Scope.Add("r_basicprofile");
            //linkedinAuthenticationOptions.Scope.Add("r_emailaddress");

            app.UseLinkedInAuthentication(linkedinAuthenticationOptions);
            #endregion

            #region Facebook

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["FacebookAppSecretKey"],
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
                //UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,email"
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,first_name,last_name,email"
            };

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

            app.UseFacebookAuthentication(facebookAuthenticationOptions);
            #endregion

            #region Google

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GoogleClientId"],
                ClientSecret = ConfigurationManager.AppSettings["GoogleClientSecretKey"],
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                }
            };

            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login profile");

            app.UseGoogleAuthentication(googleAuthenticationOptions);
            #endregion
        }
Пример #24
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(DBContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            googleAuthOptions = new GooglePlusAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GooglePlusClientId"],
                ClientSecret = ConfigurationManager.AppSettings["GooglePlusClientSecret"],
                Provider     = new GoogleAuthProvider(),
                CallbackPath = new PathString("/signin-googleplus")
            };
            // TODO uncomment to use G+ auth
            app.UseGooglePlusAuthentication(googleAuthOptions);

            string stripeClientId     = ConfigurationManager.AppSettings["StripeClientId"];
            string stripeClientSecret = ConfigurationManager.AppSettings["StripeClientSecret"];

            stripeAuthOptions = new StripeAuthenticationOptions()
            {
                ClientId     = stripeClientId,
                ClientSecret = stripeClientSecret,
                Provider     = new StripeAuthProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                        context.Identity.AddClaim(new Claim("urn:stripe:refreshToken", context.RefreshToken));
                    }
                },
                SignInAsAuthenticationType = Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie
            };
            app.UseStripeAuthentication(stripeAuthOptions);



            string linkedinApiKey = ConfigurationManager.AppSettings["LinkedInApiKey"];
            string linkedinSecret = ConfigurationManager.AppSettings["LinkedInSecret"];

            linkedinAuthOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = linkedinApiKey,
                ClientSecret = linkedinSecret,
                Provider     = new LinkedInAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };
            app.UseLinkedInAuthentication(linkedinAuthOptions);


            string githubClientId     = ConfigurationManager.AppSettings["GithubClientId"];
            string githubClientSecret = ConfigurationManager.AppSettings["GithubClientSecret"];

            githubAuthOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = githubClientId,
                ClientSecret = githubClientSecret,
                Provider     = new GitHubAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseGitHubAuthentication(githubAuthOptions);

            string twitterConsumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            string twitterConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

            twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = githubClientId,
                ConsumerSecret = githubClientSecret,
                Provider       = new TwitterAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseTwitterAuthentication(twitterAuthOptions);


            string stackexchangeClientId     = ConfigurationManager.AppSettings["StackExchangeClientId"];
            string stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecret"];
            string stackexchangeKey          = ConfigurationManager.AppSettings["StackExchangeKey"];

        #if DEBUG
            stackexchangeClientId     = ConfigurationManager.AppSettings["StackExchangeClientIdDEBUG"];
            stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecretDEBUG"];
            stackexchangeKey          = ConfigurationManager.AppSettings["StackExchangeKeyDEBUG"];
        #endif

            stackexchangeAuthOptions = new StackExchangeAuthenticationOptions()
            {
                ClientId     = stackexchangeClientId,
                ClientSecret = stackexchangeClientSecret,
                Key          = stackexchangeKey,
                Provider     = new StackExchangeAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseStackExchangeAuthentication(stackexchangeAuthOptions);


            //Configure Facebook External Login
            //facebookAuthOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "xxx",
            //    AppSecret = "xxx",
            //    Provider = new FacebookAuthProvider()
            //};
            //app.UseFacebookAuthentication(facebookAuthOptions);
        }
Пример #25
0
        // Per altre informazioni su come configurare l'autenticazione, vedere https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configurare il contesto di database, la gestione utenti e la gestione accessi in modo da usare un'unica istanza per richiesta
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Consentire all'applicazione di utilizzare un cookie per memorizzare informazioni relative all'utente connesso
            // e per memorizzare temporaneamente le informazioni relative a un utente che accede tramite un provider di accesso di terze parti
            // Configurare il cookie di accesso
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Consente all'applicazione di convalidare l'indicatore di sicurezza quando l'utente esegue l'accesso.
                    // Questa funzionalità di sicurezza è utile quando si cambia una password o si aggiungono i dati di un account di accesso esterno all'account personale.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser, long>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (id.GetUserId <long>()))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Consente all'applicazione di memorizzare temporaneamente le informazioni dell'utente durante la verifica del secondo fattore nel processo di autenticazione a due fattori.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Consente all'applicazione di memorizzare il secondo fattore di verifica dell'accesso, ad esempio il numero di telefono o l'indirizzo e-mail.
            // Una volta selezionata questa opzione, il secondo passaggio di verifica durante la procedura di accesso viene memorizzato sul dispositivo usato per accedere.
            // È simile all'opzione RememberMe disponibile durante l'accesso.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Rimuovere il commento dalle seguenti righe per abilitare l'accesso con provider di accesso di terze parti
            app.UseMicrosoftAccountAuthentication(
                clientId: "xxxxxxxxxxxxxxxxxx",
                clientSecret: "xxxxxxxxxxxxxxxxxx");


            app.UseTwitterAuthentication(
                consumerKey: "xxxxxxxxxxxxxxxxxx",
                consumerSecret: "xxxxxxxxxxxxxxxxxx");

            var facebookOptions = new FacebookAuthenticationOptions
            {
                AppId     = "xxxxxxxxxxxxxxxxxx",
                AppSecret = "xxxxxxxxxxxxxxxxxx",
                //BackchannelHttpHandler = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.11/me?fields=id,email,picture",
                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
                        context.Identity.AddClaim(new Claim("urn:facebook:email", context.Email, ClaimValueTypes.Email, "Facebook"));
                        return(Task.FromResult(0));
                    }
                },
            };

            facebookOptions.Scope.Add("email");
            facebookOptions.Scope.Add("user_friends");
            //facebookOptions.Scope.Add("friends_about_me");
            //facebookOptions.Scope.Add("friends_photos");
            app.UseFacebookAuthentication(facebookOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "xxxxxxxxxxxxxxxxxx",
                ClientSecret = "xxxxxxxxxxxxxxxxxx"
            });

            var linkedInOptions = new LinkedInAuthenticationOptions
            {
                ClientId     = "xxxxxxxxxxxxxxxxxx",
                ClientSecret = "xxxxxxxxxxxxxxxxxx",
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new Claim("urn:linkedin:accesstoken", context.AccessToken, ClaimValueTypes.String, "LinkedIn"));
                        context.Identity.AddClaim(new Claim("urn:linkedin:name", context.Name));
                        context.Identity.AddClaim(new Claim("urn:linkedin:email", context.Email, ClaimValueTypes.Email, "LinkedIn"));
                        context.Identity.AddClaim(new Claim("urn:linkedin:id", context.Id));
                        return(Task.FromResult(0));
                    }
                },
            };

            app.UseLinkedInAuthentication(linkedInOptions);


            //app.UseYahooAuthentication("", "");

            //app.UseInstagramInAuthentication("", "");

            //var options = new GooglePlusAuthenticationOptions
            //{
            //    ClientId = "",
            //    ClientSecret = "",
            //    RequestOfflineAccess = true,
            //    Provider = new GooglePlusAuthenticationProvider
            //    {
            //        OnAuthenticated = async context => System.Diagnostics.Debug.WriteLine(String.Format("Refresh Token: {0}", context.RefreshToken))
            //    }
            //};
            //options.MomentTypes.Add("http://schemas.google.com/AddActivity");
            //options.MomentTypes.Add("http://schemas.google.com/CheckInActivity");
            //options.MomentTypes.Add("http://schemas.google.com/BuyActivity");
            //app.UseGooglePlusAuthentication(options);

            //app.UseOpenIDAuthentication("http://me.yahoo.com/", "Yahoo");

            //app.UseOpenIDAuthentication("https://www.google.com/accounts/o8/id", "Google");

            //app.UseDropboxAuthentication(
            //    appKey: "",
            //    appSecret: "");

            //app.UseFoursquareAuthentication(
            //	clientId: "",
            //	clientSecret: "");

            //app.UseFlickrAuthentication("", "");

            //app.UseSpotifyAuthentication(
            //    clientId: "",
            //    clientSecret: "");
        }
Пример #26
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseInstagramInAuthentication(new InstagramAuthenticationOptions
            //{
            //    ClientId = ConfigurationManager.AppSettings["InstagramClientId"],
            //    ClientSecret = ConfigurationManager.AppSettings["InstagramClientSecret"]
            //});

            LinkedInAuthenticationOptions linkedInAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkedInId"],
                ClientSecret = ConfigurationManager.AppSettings["LinekdInSecret"],
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:tokens:linkedin", context.AccessToken));
                        return(Task.FromResult(0));
                    }
                },

                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            // not much data available from linkedin just after app registration
            linkedInAuthenticationOptions.Scope.Add("r_basicprofile r_emailaddress");

            app.UseLinkedInAuthentication(linkedInAuthenticationOptions);


            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:tokens:facebook", context.AccessToken));
                        return(Task.FromResult(0));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                SendAppSecretProof         = true
            };

            facebookAuthenticationOptions.Scope.Add("email user_friends user_likes user_photos");

            app.UseFacebookAuthentication(facebookAuthenticationOptions);
        }
Пример #27
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            #region Microsoft

            var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                Provider     = new MicrosoftAccountAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                            }
                        }
                    }
                }
            };
            microsoftAuthenticationOptions.Scope.Add("wl.basic");
            microsoftAuthenticationOptions.Scope.Add("wl.emails");
            microsoftAuthenticationOptions.Scope.Add("wl.birthday");
            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);

            #endregion Microsoft

            #region Twitter
            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwtI"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwtS"],
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                    new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                }),
                Provider = new TwitterAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken));
                        foreach (var claim in context.UserId)
                        {
                            var    claimType  = string.Format("urn:twitter:{0}", claim);
                            string claimValue = claim.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter"));
                            }
                        }
                    }
                }
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region Facebook

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FaceI"],
                AppSecret = ConfigurationManager.AppSettings["FaceS"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }
                    }
                }
            };
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            #endregion Facebook

            #region Google

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GglI"],
                ClientSecret = ConfigurationManager.AppSettings["GglS"],
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                }
            };
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);

            #endregion Google

            #region LinkedIn

            var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkI"],
                ClientSecret = ConfigurationManager.AppSettings["LinkS"],
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:linkedin:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                            }
                        }
                    }
                }
            };
            app.UseLinkedInAuthentication(linkedinAuthenticationOptions);

            #endregion LinkedIn

            #region GitHub

            var gitAuthanticationOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GitI"],
                ClientSecret = ConfigurationManager.AppSettings["GitS"],
                Provider     = new GitHubAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:github:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub"));
                            }
                        }
                    }
                }
            };
            app.UseGitHubAuthentication(gitAuthanticationOptions);

            #endregion GitHub
        }
Пример #28
0
        public void Configuration(IAppBuilder app)
        {
            AuthSettings settings = new AuthSettings();

            #region Register Route Mappings
            PTVService.RegisterRouteMapping(app);
            #endregion Register Route Mappings

            #region Configure the Service instances, User manager and Signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            #endregion Configure the Service instances, User manager and Signin manager to use a single instance per request

            #region Configure Owin to use Authentication Cookie(s) (default behaviour)
            CookieAuthenticationOptions cookieOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval : TimeSpan.FromMinutes(30),
                        regenerateIdentity : delegate(ApplicationUserManager manager, ApplicationUser user)
                    {
                        return(user.GenerateUserIdentityAsync(manager));
                    }
                        )
                }
            };
            if (string.IsNullOrEmpty(settings.LoginPath) == false)
            {
                cookieOptions.LoginPath = new PathString(settings.LoginPath);
            }
            if (settings.ExpireTimeSpan != null)
            {
                cookieOptions.ExpireTimeSpan = settings.ExpireTimeSpan.Value;
            }
            if (settings.SlidingExpiration != null)
            {
                cookieOptions.SlidingExpiration = settings.SlidingExpiration.Value;
            }
            if (string.IsNullOrEmpty(settings.CookieDomain) == false)
            {
                cookieOptions.CookieDomain = settings.CookieDomain;
            }
            if (settings.CookieHttpOnly != null)
            {
                cookieOptions.CookieHttpOnly = (settings.CookieHttpOnly ?? true);
            }                                                                                                          // NOTE: set to 'false' to allow javascript to send Cookie information (need to send Cookie information) through to remote CORS-enabled WCF services
            if (settings.CookieAlwaysSecure != null)
            {
                cookieOptions.CookieSecure = ((settings.CookieAlwaysSecure == null) ? CookieSecureOption.SameAsRequest : (settings.CookieAlwaysSecure == true) ? CookieSecureOption.Always : CookieSecureOption.Never);
            }
            // Enable the application to use a cookie to store information for the signed in user and to use a cookie to temporarily store information about a user logging in with a third party login provider. Configure the sign in cookie
            app.UseCookieAuthentication(cookieOptions);
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            if ((settings.EnableTwoFactorAuthenticationQ ?? false) == true)
            {
                // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
                app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
                // Enables the application to remember the second login verification factor such as phone or email. Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. This is similar to the RememberMe option when you log in.
                app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            }
            else
            {
            }
            #endregion Configure Owin to use Authentication Cookie(s) (default behaviour)

            #region Configure additional OAuth Authentication Providers
#if AUTH_GOOGLE
            if (string.IsNullOrEmpty(settings.Google_AppId) == false && string.IsNullOrEmpty(settings.Google_Secret) == false && string.IsNullOrEmpty(settings.Google_CallbackPath) == false)
            {
                GoogleOAuth2AuthenticationOptions options = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = settings.Google_AppId,
                    ClientSecret = settings.Google_Secret,
                    Scope        = { "openid", "profile", "email" }, // , "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email"
                    CallbackPath = new PathString(settings.Google_CallbackPath),
                    Provider     = new CustomGoogleOAuth2AuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomGoogleBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseGoogleAuthentication(options);
            }
#endif
#if AUTH_FACEBOOK
            if (string.IsNullOrEmpty(settings.Facebook_AppId) == false && string.IsNullOrEmpty(settings.Facebook_Secret) == false && string.IsNullOrEmpty(settings.Facebook_CallbackPath) == false)
            {
                FacebookAuthenticationOptions options = new FacebookAuthenticationOptions()
                {
                    AppId                      = settings.Facebook_AppId,
                    AppSecret                  = settings.Facebook_Secret,
                    Scope                      = { "email", "public_profile", }, //, "user_friends"
                    CallbackPath               = new PathString(settings.Facebook_CallbackPath),
                    Provider                   = new CustomFacebookAuthenticationProvider(),
                    BackchannelHttpHandler     = new CustomFacebookBackChannelHandler(),                                                                              //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    UserInformationEndpoint    = $@"https://graph.facebook.com/{settings.Facebook_ApiVersion}/me?fields=id,name,email,first_name,last_name,location", //$@"https://graph.facebook.com/me?fields=id,email,first_name,last_name", //,company
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseFacebookAuthentication(options);
            }
#endif
#if AUTH_MICROSOFT
            if (string.IsNullOrEmpty(settings.Microsoft_AppId) == false && string.IsNullOrEmpty(settings.Microsoft_Secret) == false && string.IsNullOrEmpty(settings.Microsoft_CallbackPath) == false)
            {
                MicrosoftAccountAuthenticationOptions options = new MicrosoftAccountAuthenticationOptions()
                {
                    ClientId     = settings.Microsoft_AppId,
                    ClientSecret = settings.Microsoft_Secret,
                    CallbackPath = new PathString(settings.Microsoft_CallbackPath),
                    Scope        = { "User.Read", }, // "wl.basic", "wl.emails"
                    Provider     = new CustomMicrosoftAccountAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomMicrosoftBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseMicrosoftAccountAuthentication(options);
            }
#endif
#if AUTH_LINKEDIN
            if (string.IsNullOrEmpty(settings.LinkedIn_AppId) == false && string.IsNullOrEmpty(settings.LinkedIn_Secret) == false && string.IsNullOrEmpty(settings.LinkedIn_CallbackPath) == false)
            {
                LinkedInAuthenticationOptions options = new LinkedInAuthenticationOptions()
                {
                    ClientId     = settings.LinkedIn_AppId,
                    ClientSecret = settings.LinkedIn_Secret,
                    CallbackPath = new PathString(settings.LinkedIn_CallbackPath),
                    //Scope = { "r_basicprofile", "r_emailaddress", }, //Scope = (IList<string>)(settings.LinkedIn_Scope ?? new string[] { "r_basicprofile" }).ToList(),
                    Provider = new CustomLinkedInAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomLinkedInBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseLinkedInAuthentication(options);
            }
#endif
#if AUTH_TWITTER
            if (string.IsNullOrEmpty(settings.Twitter_AppId) == false && string.IsNullOrEmpty(settings.Twitter_Secret) == false && string.IsNullOrEmpty(settings.Twitter_CallbackPath) == false)
            {
                TwitterAuthenticationOptions options = new TwitterAuthenticationOptions()
                {
                    ConsumerKey    = settings.Twitter_AppId,
                    ConsumerSecret = settings.Twitter_Secret,
                    CallbackPath   = new PathString(settings.Twitter_CallbackPath),
                    //Scope = { "read", "email", },
                    Provider = new CustomTwitterAuthenticationProvider(),
                    BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType      = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseTwitterAuthentication(options);
            }
#endif
#if AUTH_GITHUB
            if (string.IsNullOrEmpty(settings.GitHub_AppId) == false && string.IsNullOrEmpty(settings.GitHub_Secret) == false && string.IsNullOrEmpty(settings.GitHub_CallbackPath) == false)
            {
                GitHubAuthenticationOptions options = new GitHubAuthenticationOptions()
                {
                    ClientId     = settings.GitHub_AppId,
                    ClientSecret = settings.GitHub_Secret,
                    CallbackPath = new PathString(settings.GitHub_CallbackPath),
                    Scope        = { "user", },
                    Provider     = new CustomGitHubAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomGitHubBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseGitHubAuthentication(options);
            }
#endif
            #endregion Configure additional OAuth Authentication Providers
        }