コード例 #1
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // 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: "",
            //    clientSecret: "");

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

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

            //app.UseGoogleAuthentication();
        }
コード例 #2
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

            // 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);
        }
コード例 #3
0
 public UserRepository(IDataProtectionProvider dataProtectionProvider, IUnitOfWork unitOfWork)
 {
     _userStore = new UserStore<ApplicationUser>(unitOfWork._dbContext);
     _unitOfWork = unitOfWork;
     _securityQuestionRepository = new RepositoryBase<SecurityQuestion>(unitOfWork);
     _userStore.UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
 }
コード例 #4
0
ファイル: Startup.cs プロジェクト: johncoffee/eventblock
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Login")
        });

        DataProtectionProvider = app.GetDataProtectionProvider();

        //HttpConfiguration config = new HttpConfiguration();
        //config.MapHttpAttributeRoutes();

        ////config.Routes.MapHttpRoute(
        ////    name: "DefaultApi",
        ////    routeTemplate: "api/{controller}/{id}",
        ////    defaults: new { id = RouteParameter.Optional }
        ////);

        //app.UseWebApi(config);

        ImageResizer.Configuration.Config.Current.Pipeline.RewriteDefaults +=
            delegate(IHttpModule m, HttpContext c, ImageResizer.Configuration.IUrlEventArgs args)
            {
                if (args.VirtualPath.IndexOf("/images/", StringComparison.OrdinalIgnoreCase) > -1)
                    args.QueryString["404"] = "~/images/404.png";
            };
    }
コード例 #5
0
ファイル: Startup.cs プロジェクト: tjarita/DogeDaycare
        public void Configuration(IAppBuilder app)
        {
            app.UseAbp();

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            if (IsTrue("ExternalAuth.Facebook.IsEnabled"))
            {
                app.UseFacebookAuthentication(CreateFacebookAuthOptions());
            }

            if (IsTrue("ExternalAuth.Twitter.IsEnabled"))
            {
                app.UseTwitterAuthentication(CreateTwitterAuthOptions());
            }

            if (IsTrue("ExternalAuth.Google.IsEnabled"))
            {
                app.UseGoogleAuthentication(CreateGoogleAuthOptions());
            }

            app.MapSignalR();
        }
コード例 #6
0
ファイル: OAuthInstaller.cs プロジェクト: CoditEU/lunchorder
        public OAuthInstaller(IDataProtectionProvider dataProtectionProvider)
        {
            if (dataProtectionProvider == null)
                dataProtectionProvider = new DpapiDataProtectionProvider();

            _dataProtectionProvider = dataProtectionProvider;
        }
コード例 #7
0
ファイル: OwinConfig.cs プロジェクト: sweeperq/Badger
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<DbContext>(() => DependencyResolver.Current.GetService<DbContext>());
            app.CreatePerOwinContext<UserManager<User, int>>(() => DependencyResolver.Current.GetService<UserManager<User, int>>());
            app.CreatePerOwinContext<SignInManager<User, int>>(() => DependencyResolver.Current.GetService<SignInManager<User, int>>());

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieHttpOnly = true,
                CookieName = "Badger",
                ExpireTimeSpan = TimeSpan.FromDays(30),
                LoginPath = new PathString("/Account/SignIn"),
                LogoutPath = new PathString("/Account/SignOut"),
                ReturnUrlParameter = "ReturnUrl",
                SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<User,int>, User, int>(
                        validateInterval: TimeSpan.FromMinutes(1),
                        regenerateIdentityCallback: (manager, user) =>
                        user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (id.GetUserId<int>()))
                }
            });
        }
コード例 #8
0
 public SiteDataProtector(
     IDataProtectionProvider dataProtectionProvider,
     ILogger<SiteDataProtector> logger)
 {
     rawProtector = dataProtectionProvider.CreateProtector("cloudscribe.Core.Models.SiteSettings");
     log = logger;
 }
コード例 #9
0
ファイル: OwinConfig.cs プロジェクト: sweeperq/Mendota
        public void Configuration(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaContext>());
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaUserManager>());
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<MendotaSignInManager>());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieHttpOnly = true,
                CookieName = "Mendota",
                ExpireTimeSpan = TimeSpan.FromDays(14),
                LoginPath = new PathString("/Account/Login"),
                LogoutPath = new PathString("/Account/Logout"),
                ReturnUrlParameter = "ReturnUrl",
                SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MendotaUserManager, User, int>(
                        validateInterval: TimeSpan.FromMinutes(2),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (id.GetUserId<int>()))
                }
            });

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(10));
        }
コード例 #10
0
ファイル: Startup.Auth.cs プロジェクト: Budzyn/hunter
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext(CreateKernel);
            app.UseNinjectMiddleware(CreateKernel);
            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),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AccessTokenFormat = new HunterJwtFormat("http://localhost:53147/"),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            //app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseLinkedInAuthentication(
            //    "<YOUR API KEY>",
            //    "<YOUR SECRET KEY>"
            //    );
        }
コード例 #11
0
ファイル: IdentityStartup.cs プロジェクト: bpug/MetronaWT
        // Weitere Informationen zum Konfigurieren der Authentifizierung finden Sie unter "http://go.microsoft.com/fwlink/?LinkId=301864".
        public static void ConfigureAuth(IAppBuilder app)
        {
            // Konfigurieren des db-Kontexts, des Benutzer-Managers und des Anmelde-Managers für die Verwendung einer einzelnen Instanz pro Anforderung.
            //app.CreatePerOwinContext(MyDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance<ApplicationUserManager>());

            // Anwendung für die Verwendung eines Cookies zum Speichern von Informationen für den angemeldeten Benutzer aktivieren
            // und ein Cookie zum vorübergehenden Speichern von Informationen zu einem Benutzer zu verwenden, der sich mit dem Anmeldeanbieter eines Drittanbieters anmeldet.
            // Konfigurieren des Anmeldecookies.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Aktiviert die Anwendung für die Überprüfung des Sicherheitsstempels, wenn sich der Benutzer anmeldet.
                    // Dies ist eine Sicherheitsfunktion, die verwendet wird, wenn Sie ein Kennwort ändern oder Ihrem Konto eine externe Anmeldung hinzufügen. 

                   OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, long>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => manager.GenerateUserIdentityAsync(user),
                        getUserIdCallback: (claim) => long.Parse(claim.GetUserId()))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Aktiviert die Anwendung für das vorübergehende Speichern von Benutzerinformationen beim Überprüfen der zweiten Stufe im zweistufigen Authentifizierungsvorgang.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Aktiviert die Anwendung für das Speichern der zweiten Anmeldeüberprüfungsstufe (z. B. Telefon oder E-Mail).
            // Wenn Sie diese Option aktivieren, wird Ihr zweiter Überprüfungsschritt während des Anmeldevorgangs auf dem Gerät gespeichert, von dem aus Sie sich angemeldet haben.
            // Dies ähnelt der RememberMe-Option bei der Anmeldung.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Auskommentierung der folgenden Zeilen aufheben, um die Anmeldung mit Anmeldeanbietern von Drittanbietern zu ermöglichen
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
コード例 #12
0
        public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider)
        {
            if (dataProtectionProvider == null)
            {
                dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
            }

            _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1"));
        }
 /// <summary>
 /// Initializes a new <see cref="T:Microsoft.AspNet.Authentication.Google.GoogleAuthenticationMiddleware"/>.
 /// 
 /// </summary>
 /// <param name="next">The next middleware in the HTTP pipeline to invoke.</param><param name="dataProtectionProvider"/><param name="loggerFactory"/><param name="encoder"/><param name="sharedOptions"/><param name="options">Configuration options for the middleware.</param><param name="configureOptions"/>
 public MyGoogleAuthenticationMiddleware(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, IUrlEncoder encoder, IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<GoogleAuthenticationOptions> options, ConfigureOptions<GoogleAuthenticationOptions> configureOptions = null)
     : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options, configureOptions)
 {
     if (this.Options.Scope.Count != 0)
         return;
     this.Options.Scope.Add("openid");
     this.Options.Scope.Add("profile");
     this.Options.Scope.Add("email");
 }
コード例 #14
0
        public static IDataProtector CreateDataProtector(IDataProtectionProvider dataProtectionProvider, params string[] purposes)
        {
            if (dataProtectionProvider == null)
            {
                dataProtectionProvider = DataProtectionProvider.CreateFromDpapi();
            }

            return dataProtectionProvider.CreateProtector(string.Join(";", purposes));
        }
コード例 #15
0
        public DefaultAntiforgeryTokenSerializer(IDataProtectionProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            _cryptoSystem = provider.CreateProtector(Purpose);
        }
        public void SetUp()
        {
            var userStoreMock = MockRepository.GenerateMock<IUserStore<ApplicationUser>>();
            var dataProtector = MockRepository.GenerateMock<IDataProtector>();
            dataProtectionProviderMock = MockRepository.GenerateMock<IDataProtectionProvider>();
            dataProtectionProviderMock.Expect(mock => mock.Create(Arg<string>.Is.Anything)).Return(dataProtector);
            applicationUserManagerMock = MockRepository.GenerateMock<ApplicationUserManager>(userStoreMock, dataProtectionProviderMock);
            gamingGroupSaverMock = MockRepository.GenerateMock<IGamingGroupSaver>();
            configurationManagerMock = MockRepository.GenerateMock<IConfigurationManager>();
            dataContextMock = MockRepository.GenerateMock<IDataContext>();

            firstTimeAuthenticator = new FirstTimeAuthenticator(
                gamingGroupSaverMock,
                applicationUserManagerMock,
                configurationManagerMock,
                dataContextMock);

            applicationUser = new ApplicationUser
            {
                Id = "user id",
                UserName = "******"
            };

            registrationSource = TransactionSource.RestApi;

            var appSettingsMock = MockRepository.GenerateMock<IAppSettings>();
            configurationManagerMock.Expect(mock => mock.AppSettings)
                                    .Return(appSettingsMock);
            appSettingsMock.Expect(mock => mock.Get(FirstTimeAuthenticator.APP_KEY_EMAIL_CONFIRMATION_CALLBACK_URL))
                           .Return(callbackUrl);

            expectedNewlyCreatedGamingGroupResult = new NewlyCreatedGamingGroupResult
            {
                NewlyCreatedGamingGroup = new GamingGroup {  Id = 1 },
                NewlyCreatedPlayer = new Player { Id = 100, Name = "some awesome player name"}
            };
            gamingGroupSaverMock.Expect(mock => mock.CreateNewGamingGroup(
                                                                          Arg<string>.Is.Anything,
                                                                          Arg<TransactionSource>.Is.Anything,
                                                                          Arg<ApplicationUser>.Is.Anything))
                                .Return(expectedNewlyCreatedGamingGroupResult);

            applicationUserManagerMock.Expect(mock => mock.GenerateEmailConfirmationTokenAsync(applicationUser.Id))
                                      .Return(Task.FromResult(confirmationToken));

            string expectedCallbackUrl = callbackUrl + string.Format(
                                                                     FirstTimeAuthenticator.CONFIRMATION_EMAIL_CALLBACK_URL_SUFFIX,
                                                                     applicationUser.Id,
                                                                     HttpUtility.UrlEncode(confirmationToken));
            string expectedEmailBody = string.Format(FirstTimeAuthenticator.CONFIRMATION_EMAIL_BODY, expectedCallbackUrl);
            applicationUserManagerMock.Expect(mock => mock.SendEmailAsync(
                                                                          applicationUser.Id,
                                                                          FirstTimeAuthenticator.EMAIL_SUBJECT,
                                                                          expectedEmailBody))
                                      .Return(Task.FromResult(-1));
        }
コード例 #17
0
        private ApplicationUserManager BuildUserManager(IComponentContext context, IEnumerable<Parameter> parameters, IDataProtectionProvider dataProtectionProvider)
        {
            var manager = new ApplicationUserManager(context.Resolve<IUserStore<ApplicationUser, int>>());

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
        public UserProfileAuthenticatorDataRepository(IDataProtectionProvider dataProtectionProvider, IEnrollmentClient enrollmentService, ILoggerFactory loggerFactory)
        {
            if (dataProtectionProvider == null) throw new ArgumentNullException(nameof(dataProtectionProvider));
            if (enrollmentService == null) throw new ArgumentNullException(nameof(enrollmentService));
            if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));

            _dataProtector = dataProtectionProvider.CreateProtector(GetType().FullName);
            _enrollmentservice = enrollmentService;
            _logger = loggerFactory.CreateLogger<UserProfileAuthenticatorDataRepository>();
        }
コード例 #19
0
        public DataProtectionProviderProtectedData(IDataProtectionProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            _provider = provider;
            _connectionTokenProtector = provider.CreateProtector(Purposes.ConnectionToken);
            _groupsProtector = provider.CreateProtector(Purposes.Groups);
        }
コード例 #20
0
ファイル: Startup.Auth.cs プロジェクト: Jaer86/RedNuc
        // Para obtener más información para configurar la autenticación, visite http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure el contexto de base de datos, el administrador de usuarios y el administrador de inicios de sesión para usar una única instancia por solicitud
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Permitir que la aplicación use una cookie para almacenar información para el usuario que inicia sesión
            // y una cookie para almacenar temporalmente información sobre un usuario que inicia sesión con un proveedor de inicio de sesión de terceros
            // Configurar cookie de inicio de sesión
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Permite a la aplicación validar la marca de seguridad cuando el usuario inicia sesión.
                    // Es una característica de seguridad que se usa cuando se cambia una contraseña o se agrega un inicio de sesión externo a la cuenta.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Permite que la aplicación almacene temporalmente la información del usuario cuando se verifica el segundo factor en el proceso de autenticación de dos factores.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Permite que la aplicación recuerde el segundo factor de verificación de inicio de sesión, como el teléfono o correo electrónico.
            // Cuando selecciona esta opción, el segundo paso de la verificación del proceso de inicio de sesión se recordará en el dispositivo desde el que ha iniciado sesión.
            // Es similar a la opción Recordarme al iniciar sesión.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Quitar los comentarios de las siguientes líneas para habilitar el inicio de sesión con proveedores de inicio de sesión de terceros
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
コード例 #21
0
ファイル: Startup.Auth.cs プロジェクト: edikep2000/Zakar
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
          

            // 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, IdentityUser, Int32>(
                      validateInterval: TimeSpan.FromMinutes(30),
                      regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                      getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
                }
            });            
            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 = ""
            //});
        }
コード例 #22
0
        public void Configuration(IAppBuilder app)
        {
            dataProtectionProvider = app.GetDataProtectionProvider();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                CookieName = "CloudCentreApp",
                //ExpireTimeSpan = System.TimeSpan.FromMinutes(10)
            });
        }
コード例 #23
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {

            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

            // 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: "000000004013A8D8",
                clientSecret: "5WdUBURuFxFwMa9v97z-qbEXzvq42Nf9");

            app.UseTwitterAuthentication(
               consumerKey: "0000000044116236",
               consumerSecret: "nLut0Tya491C9y9m0bdmAPrbbrnS41yJ");

            app.UseFacebookAuthentication(
               appId: "0000000044116236",
               appSecret: "nLut0Tya491C9y9m0bdmAPrbbrnS41yJ");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "654419548573-ik27lh6k0ml1r9urk6g83d9aqk3un8kl.apps.googleusercontent.com",
                ClientSecret = "GLGWXVGCiilth7kncoIMaAP0"
            });
        }
コード例 #24
0
        public TicketDataFormatTokenValidator(IDataProtectionProvider dataProtectionProvider)
        {
            if (dataProtectionProvider == null)
            {
               #if DNXCORE50
                dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer");
               #else
                dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.Machine))).CreateProtector("OAuth.AspNet.AuthServer");
               #endif
            }

            _ticketDataFormat = new TicketDataFormat(dataProtectionProvider.CreateProtector("Access_Token", "v1"));
        }
コード例 #25
0
ファイル: Startup.cs プロジェクト: andrewQwer/PotionMaking
        public void ConfigureAuth(IAppBuilder app)
        {
            Database.SetInitializer<ApplicationDbContext>(null);
            DataProtectionProvider = app.GetDataProtectionProvider();
            // Configure the db context, user manager and role
            // manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            // 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 OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new CustomOAuthProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // 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();
        }
コード例 #26
0
        public void SetUp()
        {
            this.actionExecutingContext = new ActionExecutingContext
            {
                ActionParameters = new Dictionary<string, object>()
            };
            this.userStoreMock = MockRepository.GenerateMock<IUserStore<ApplicationUser>>();
            this.dataProtectionProviderMock = MockRepository.GenerateMock<IDataProtectionProvider>();
            var dataProtector = MockRepository.GenerateMock<IDataProtector>();
            this.dataProtectionProviderMock.Expect(mock => mock.Create(Arg<string>.Is.Anything)).Return(dataProtector);
            this.userManager = new ApplicationUserManager(this.userStoreMock, this.dataProtectionProviderMock);
            clientIdCalculatorMock = MockRepository.GenerateMock<ClientIdCalculator>();
            //need to simulate like the parameter exists on the method
            this.actionExecutingContext.ActionParameters[UserContextAttribute.USER_CONTEXT_KEY] = null;

            HttpContextBase httpContextBase = MockRepository.GenerateMock<HttpContextBase>();
            this.actionExecutingContext.HttpContext = httpContextBase;

            IPrincipal principal = MockRepository.GenerateMock<IPrincipal>();
            httpContextBase.Expect(contextBase => contextBase.User)
                .Repeat.Any()
                .Return(principal);
            this.identity = MockRepository.GenerateMock<IIdentity>();
            principal.Expect(mock => mock.Identity)
                .Repeat.Any()
                .Return(this.identity);
            this.identity.Expect(mock => mock.IsAuthenticated)
                .Repeat.Once()
                .Return(true);

            HttpRequestBase requestBaseMock = MockRepository.GenerateMock<HttpRequestBase>();

            httpContextBase.Expect(mock => mock.Request)
                .Return(requestBaseMock);
            this.requestParameters = new NameValueCollection();
            requestBaseMock.Expect(mock => mock.Params)
                .Return(this.requestParameters);

            this.userContextActionFilter = new UserContextAttribute();
            this.applicationUser = new ApplicationUser()
            {
                Id = "user id",
                CurrentGamingGroupId = 315
            };
            Task<ApplicationUser> task = Task.FromResult(this.applicationUser);
            //TODO can't figure out how to mock the GetUserId() extension method, so have to be less strict here
            this.userStoreMock.Expect(mock => mock.FindByIdAsync(Arg<string>.Is.Anything))
                .Repeat.Once()
                .Return(task);
        }
コード例 #27
0
        /// <summary>
        /// Creates an <see cref="DataProtectionProvider"/> given a location at which to store keys and an
        /// optional configuration callback.
        /// </summary>
        /// <param name="keyDirectory">The <see cref="DirectoryInfo"/> in which keys should be stored. This may
        /// represent a directory on a local disk or a UNC share.</param>
        /// <param name="configure">An optional callback which provides further configuration of the data protection
        /// system. See <see cref="DataProtectionConfiguration"/> for more information.</param>
        public DataProtectionProvider([NotNull] DirectoryInfo keyDirectory, Action<DataProtectionConfiguration> configure)
        {
            // build the service collection
            ServiceCollection serviceCollection = new ServiceCollection();
            serviceCollection.AddDataProtection();
            serviceCollection.ConfigureDataProtection(configurationObject =>
            {
                configurationObject.PersistKeysToFileSystem(keyDirectory);
                configure?.Invoke(configurationObject);
            });

            // extract the provider instance from the service collection
            _innerProvider = serviceCollection.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
        }
 /// <summary>
 /// Initializes a new <see cref="T:Microsoft.AspNet.Authentication.Facebook.FacebookAuthenticationMiddleware"/>.
 /// 
 /// </summary>
 /// <param name="next">The next middleware in the HTTP pipeline to invoke.</param><param name="dataProtectionProvider"/><param name="loggerFactory"/><param name="encoder"/><param name="sharedOptions"/><param name="options">Configuration options for the middleware.</param><param name="configureOptions"/>
 public MyFacebookAuthenticationMiddleware(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, IUrlEncoder encoder, IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<FacebookAuthenticationOptions> options, ConfigureOptions<FacebookAuthenticationOptions> configureOptions = null)
     : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options, configureOptions)
 {
     if (string.IsNullOrEmpty(this.Options.AppId))
         throw new ArgumentException(string.Format((IFormatProvider)CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, new object[1]
         {
             (object) "AppId"
         }));
     if (string.IsNullOrEmpty(this.Options.AppSecret))
         throw new ArgumentException(string.Format((IFormatProvider)CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, new object[1]
         {
             (object) "AppSecret"
         }));
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of <see cref="Tailspin.Surveys.TokenStorage.DistributedTokenCacheService"/>
 /// </summary>
 /// <param name="contextAccessor">An instance of <see cref="Microsoft.AspNetCore.Http.IHttpContextAccessor"/> used to get access to the current HTTP context.</param>
 /// <param name="loggerFactory"><see cref="Microsoft.Extensions.Logging.ILoggerFactory"/> used to create type-specific <see cref="Microsoft.Extensions.Logging.ILogger"/> instances.</param>
 /// <param name="dataProtectionProvider">An <see cref="Microsoft.AspNetCore.DataProtection.IDataProtectionProvider"/> for creating a data protector.</param>
 public DistributedTokenCacheService(
     IDistributedCache distributedCache,
     IHttpContextAccessor contextAccessor,
     ILoggerFactory loggerFactory,
     IDataProtectionProvider dataProtectionProvider)
     : base(loggerFactory)
 {
     Guard.ArgumentNotNull(distributedCache, nameof(distributedCache));
     Guard.ArgumentNotNull(contextAccessor, nameof(contextAccessor));
     Guard.ArgumentNotNull(dataProtectionProvider, nameof(dataProtectionProvider));
     _distributedCache = distributedCache;
     _contextAccessor = contextAccessor;
     _dataProtectionProvider = dataProtectionProvider;
 }
 public OpenIdConnectMiddlewareForTestingAuthenticate(
     RequestDelegate next,
     IDataProtectionProvider dataProtectionProvider,
     ILoggerFactory loggerFactory,
     IUrlEncoder encoder,
     IServiceProvider services,
     IOptions<SharedAuthenticationOptions> sharedOptions,
     OpenIdConnectOptions options,
     IHtmlEncoder htmlEncoder,
     OpenIdConnectHandler handler = null
     )
 : base(next, dataProtectionProvider, loggerFactory, encoder, services, sharedOptions, options, htmlEncoder)
 {
     _handler = handler;
 }
コード例 #31
0
ファイル: HomeController.cs プロジェクト: Unipisa/eligere
        public HomeController(ILogger <HomeController> logger, IWebHostEnvironment env, PersistentStores stores, IDataProtectionProvider provider)
        {
            _logger         = logger;
            contentRootPath = env.ContentRootPath;
            stores.SetContentRootPath(env.ContentRootPath);
            _conf          = stores.Configuration;
            secureBallot   = stores.SecureBallot;
            egSecureBallot = stores.EGSecureBallot;
            dataProtector  = provider;

            var confAPI = new VotingSystemConfiguration();

            lock (_conf)
            {
                var v = _conf.Get(APIConfigurationKey);
                if (v != null)
                {
                    confAPI = VotingSystemConfiguration.FromJson(v);
                }
            }
            if (confAPI.GuardianAPI != null && confAPI.MediatorAPI != null)
            {
                GuardianApi = new ElectionGuard.GuardianClient(confAPI.GuardianAPI);
                MediatorApi = new ElectionGuard.MediatorClient(confAPI.MediatorAPI);
            }
        }
コード例 #32
0
        public static ApplicationUserManager Create(ApplicationDbContext context, IDataProtectionProvider dataProtectionProvider = null)
        {
            #region Contracts

            if (context == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            // 建立使用者管理員
            var userManager = new ApplicationUserManager(context);
            if (userManager == null)
            {
                throw new InvalidOperationException();
            }

            // 設定使用者名稱的驗證邏輯
            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // 設定密碼的驗證邏輯
            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 5,     // 最小長度
                RequireNonLetterOrDigit = false, // 是否需要一個非字母或是數字
                RequireDigit            = false, // 是否需要一個數字
                RequireLowercase        = false, // 是否需要一個小寫字母
                RequireUppercase        = false, // 是否需要一個大寫字母
            };

            // 設定使用者鎖定詳細資料
            userManager.UserLockoutEnabledByDefault          = true;
            userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            userManager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 註冊雙因素驗證提供者。此應用程式使用手機和電子郵件接收驗證碼以驗證使用者
            // 您可以撰寫專屬提供者,並將它外掛到這裡。
            userManager.RegisterTwoFactorProvider("電話代碼", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "您的安全碼為 {0}"
            });
            userManager.RegisterTwoFactorProvider("電子郵件代碼", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "安全碼",
                BodyFormat = "您的安全碼為 {0}"
            });
            userManager.EmailService = new EmailService();
            userManager.SmsService   = new SmsService();
            if (dataProtectionProvider != null)
            {
                userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }

            // 回傳
            return(userManager);
        }
コード例 #33
0
 public LoginController(IUsers users, IDataProtectionProvider dataProtectionProvider, DPPurposeStrings dPPurposeStrings)
 {
     dataProtector = dataProtectionProvider.CreateProtector(dPPurposeStrings.ClientIDKey);
     this.users    = users;
 }
コード例 #34
0
 // the 'provider' parameter is provided by DI
 public MyProtector(IDataProtectionProvider provider)
 {
     _protector = provider.CreateProtector("Contoso.MyClass.v1");
 }
コード例 #35
0
 public DateTimeOffsetConverter(IDataProtectionProvider dataProtectionProvider, IByteConverter <DateTimeOffset> byteConverter)
     : base(dataProtectionProvider.CreateProtector(_purpose), byteConverter)
 {
 }
コード例 #36
0
        /// <summary>
        /// Authorization Server middleware component which is added to an OWIN pipeline. This constructor is not
        /// called by application code directly, instead it is added by calling the the IAppBuilder UseOpenIdConnectServer
        /// extension method.
        /// </summary>
        public OpenIdConnectServerMiddleware(
            [NotNull] RequestDelegate next,
            [NotNull] ILoggerFactory loggerFactory,
            [NotNull] IDistributedCache cache,
            [NotNull] IHtmlEncoder htmlEncoder,
            [NotNull] IUrlEncoder urlEncoder,
            [NotNull] IDataProtectionProvider dataProtectionProvider,
            [NotNull] IOptions <OpenIdConnectServerOptions> options,
            [NotNull] ConfigureOptions <OpenIdConnectServerOptions> configuration)
            : base(next, options, loggerFactory, urlEncoder, configuration)
        {
            if (Options.AuthorizationCodeFormat == null)
            {
                Options.AuthorizationCodeFormat = dataProtectionProvider.CreateTicketFormat(
                    typeof(OpenIdConnectServerMiddleware).FullName,
                    Options.AuthenticationScheme, "Authentication_Code", "v1");
            }

            if (Options.AccessTokenFormat == null)
            {
                Options.AccessTokenFormat = dataProtectionProvider.CreateTicketFormat(
                    typeof(OpenIdConnectServerMiddleware).FullName,
                    Options.AuthenticationScheme, "Access_Token", "v1");
            }

            if (Options.RefreshTokenFormat == null)
            {
                Options.RefreshTokenFormat = dataProtectionProvider.CreateTicketFormat(
                    typeof(OpenIdConnectServerMiddleware).Namespace,
                    Options.AuthenticationScheme, "Refresh_Token", "v1");
            }

            if (Options.Cache == null)
            {
                Options.Cache = cache;
            }

            if (Options.HtmlEncoder == null)
            {
                Options.HtmlEncoder = htmlEncoder;
            }

            if (string.IsNullOrEmpty(Options.AuthenticationScheme))
            {
                throw new ArgumentNullException(nameof(Options.AuthenticationScheme));
            }

            if (Options.RandomNumberGenerator == null)
            {
                throw new ArgumentNullException(nameof(Options.RandomNumberGenerator));
            }

            if (Options.Provider == null)
            {
                throw new ArgumentNullException(nameof(Options.Provider));
            }

            if (Options.SystemClock == null)
            {
                throw new ArgumentNullException(nameof(Options.SystemClock));
            }

            if (Options.Issuer != null)
            {
                if (!Options.Issuer.IsAbsoluteUri)
                {
                    throw new ArgumentException("options.Issuer must be a valid absolute URI.", "options.Issuer");
                }

                // See http://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery
                if (!string.IsNullOrEmpty(Options.Issuer.Query) || !string.IsNullOrEmpty(Options.Issuer.Fragment))
                {
                    throw new ArgumentException("options.Issuer must contain no query and no fragment parts.", "options.Issuer");
                }

                // Note: while the issuer parameter should be a HTTPS URI, making HTTPS mandatory
                // in Owin.Security.OpenIdConnect.Server would prevent the end developer from
                // running the different samples in test environments, where HTTPS is often disabled.
                // To mitigate this issue, AllowInsecureHttp can be set to true to bypass the HTTPS check.
                // See http://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery
                if (!Options.AllowInsecureHttp && string.Equals(Options.Issuer.Scheme, "http", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("options.Issuer must be a HTTPS URI when " +
                                                "options.AllowInsecureHttp is not set to true.", "options.Issuer");
                }
            }
        }
コード例 #37
0
 public EmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider,
                                       IOptions <EmailConfirmationTokenProviderOptions> options) : base(dataProtectionProvider, options)
 {
 }
        public WsFederationAuthenticationMiddleware(RequestDelegate next,
                                                    IOptions <WsFederationAuthenticationOptions> options,
                                                    IOptions <SharedAuthenticationOptions> sharedOptions,
                                                    ILoggerFactory loggerFactory,
                                                    IDataProtectionProvider dataProtectionProvider,
                                                    UrlEncoder encoder)
            : base(next, options, loggerFactory, encoder)
        {
            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                Options.SignInScheme = sharedOptions.Value.SignInScheme;
            }
            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                throw new ArgumentException("Options.SignInScheme is required.");
            }

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.AuthenticationType))
            {
                Options.TokenValidationParameters.AuthenticationType = Options.SignInScheme;
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(WsFederationAuthenticationMiddleware).FullName,
                    typeof(string).FullName,
                    Options.AuthenticationScheme,
                    "v1"
                    );
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (Options.SecurityTokenHandlers == null)
            {
                Options.SecurityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            }

            if (Options.Events == null)
            {
                Options.Events = new WsFederationEvents();
            }

            Uri wreply;

            if (!Options.CallbackPath.HasValue && !string.IsNullOrEmpty(Options.Wreply) &&
                Uri.TryCreate(Options.Wreply, UriKind.Absolute, out wreply))
            {
                Options.CallbackPath = PathString.FromUriComponent(wreply);
            }

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager =
                        new StaticConfigurationManager <WsFederationConfiguration>(Options.Configuration);
                }
                else
                {
                    var httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
                    {
                        Timeout = Options.BackchannelTimeout,
                        MaxResponseContentBufferSize = 1024 * 1024 * 10
                    };
                    // 10 MB
                    Options.ConfigurationManager =
                        new ConfigurationManager <WsFederationConfiguration>(Options.MetadataAddress, httpClient);
                }
            }
        }
コード例 #39
0
 protected BaseSessionAffinityProvider(IDataProtectionProvider dataProtectionProvider, ILogger logger)
 {
     _dataProtector = dataProtectionProvider?.CreateProtector(GetType().FullName) ?? throw new ArgumentNullException(nameof(dataProtectionProvider));
     Logger         = logger ?? throw new ArgumentNullException(nameof(logger));
 }
コード例 #40
0
 public CustomEmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider, IOptions <CustomEmailConfirmationTokenProviderOptions> options, ILogger <DataProtectorTokenProvider <TUser> > logger)
     : base(dataProtectionProvider, options, logger)
 {
 }
コード例 #41
0
 public DataProtectorService(IDataProtectionProvider provider)
 {
     _dataProtector = provider.CreateProtector("PipelineSpace.Infra.CrossCutting.Security");
 }
コード例 #42
0
 public CustomHeaderSessionAffinityProvider(
     IDataProtectionProvider dataProtectionProvider,
     ILogger <CustomHeaderSessionAffinityProvider> logger)
     : base(dataProtectionProvider, logger)
 {
 }
コード例 #43
0
 /// <summary>
 /// Creates a new instance of the <see cref="OpenIddictValidationDataProtectionConfiguration"/> class.
 /// </summary>
 /// <param name="dataProtectionProvider">The ASP.NET Core Data Protection provider.</param>
 public OpenIddictValidationDataProtectionConfiguration(IDataProtectionProvider dataProtectionProvider)
 => _dataProtectionProvider = dataProtectionProvider;
コード例 #44
0
        public OpenIdConnectMiddleware(
            [NotNull] RequestDelegate next,
            [NotNull] IDataProtectionProvider dataProtectionProvider,
            [NotNull] ILoggerFactory loggerFactory,
            [NotNull] IUrlEncoder encoder,
            [NotNull] IServiceProvider services,
            [NotNull] IOptions <SharedAuthenticationOptions> sharedOptions,
            [NotNull] OpenIdConnectOptions options)
            : base(next, options, loggerFactory, encoder)
        {
            if (string.IsNullOrEmpty(Options.SignInScheme) && !string.IsNullOrEmpty(sharedOptions.Value.SignInScheme))
            {
                Options.SignInScheme = sharedOptions.Value.SignInScheme;
            }

            if (Options.HtmlEncoder == null)
            {
                Options.HtmlEncoder = services.GetHtmlEncoder();
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(OpenIdConnectMiddleware).FullName,
                    typeof(string).FullName,
                    Options.AuthenticationScheme,
                    "v1");

                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (Options.StringDataFormat == null)
            {
                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(OpenIdConnectMiddleware).FullName,
                    typeof(string).FullName,
                    Options.AuthenticationScheme,
                    "v1");

                Options.StringDataFormat = new SecureDataFormat <string>(new StringSerializer(), dataProtector);
            }

            // if the user has not set the AuthorizeCallback, set it from the redirect_uri
            if (!Options.CallbackPath.HasValue)
            {
                Uri redirectUri;
                if (!string.IsNullOrEmpty(Options.RedirectUri) && Uri.TryCreate(Options.RedirectUri, UriKind.Absolute, out redirectUri))
                {
                    // Redirect_Uri must be a very specific, case sensitive value, so we can't generate it. Instead we generate AuthorizeCallback from it.
                    Options.CallbackPath = PathString.FromUriComponent(redirectUri);
                }
            }

            if (Options.Events == null)
            {
                Options.Events = new OpenIdConnectEvents();
            }

            if (string.IsNullOrEmpty(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrEmpty(Options.ClientId))
            {
                Options.TokenValidationParameters.ValidAudience = Options.ClientId;
            }

            Backchannel = new HttpClient(Options.BackchannelHttpHandler ?? new HttpClientHandler());
            Backchannel.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft ASP.NET OpenIdConnect middleware");
            Backchannel.Timeout = Options.BackchannelTimeout;
            Backchannel.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager = new StaticConfigurationManager <OpenIdConnectConfiguration>(Options.Configuration);
                }
                else if (!(string.IsNullOrEmpty(Options.MetadataAddress) && string.IsNullOrEmpty(Options.Authority)))
                {
                    if (string.IsNullOrEmpty(Options.MetadataAddress) && !string.IsNullOrEmpty(Options.Authority))
                    {
                        Options.MetadataAddress = Options.Authority;
                        if (!Options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
                        {
                            Options.MetadataAddress += "/";
                        }

                        Options.MetadataAddress += ".well-known/openid-configuration";
                    }

                    Options.ConfigurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(Options.MetadataAddress, new OpenIdConnectConfigurationRetriever(), Backchannel);
                }
            }
        }
コード例 #45
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDataProtectionProvider provider)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

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

            var options = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >();

            app.UseRequestLocalization(options.Value);

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme   = CookieAuthenticationDefaults.AuthenticationScheme,
                CookieName             = CookieAuthenticationDefaults.CookiePrefix + CookieAuthenticationDefaults.AuthenticationScheme,
                LoginPath              = new PathString("/Account/SignIn"),
                AccessDeniedPath       = new PathString("/Account/SignIn"),
                LogoutPath             = new PathString("/Account/SignOut"),
                AutomaticAuthenticate  = true,
                AutomaticChallenge     = true,
                DataProtectionProvider = provider.CreateProtector("CustomDataProtector")
            });

            app.UseCustomAuthorization();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
コード例 #46
0
 public HomeController(EmpresaDbContext contexto, IDataProtectionProvider protectionProvider, IConfiguration configuracao)
 {
     _contexto          = contexto;
     _protectorProvider = protectionProvider.CreateProtector(configuracao.GetSection("ChaveCriptografia").Value);
     _configuracao      = configuracao;
 }
コード例 #47
0
 public LevyDeclarationCookieWriter(IHostingEnvironment hostingEnvironment, IDataProtectionProvider dataProtectionProvider, ILogger <LevyDeclarationCookieWriter> logger)
 {
     _hostingEnvironment = hostingEnvironment;
     _dataProtector      = dataProtectionProvider.CreateProtector(DataProtectionPurposes.LevyDeclarationCookie);
     _logger             = logger;
 }
コード例 #48
0
 public StorageMappingService(IDataProtectionProvider dataProtectionProvider)
 {
     _dataProtector = dataProtectionProvider.CreateProtector(nameof(StorageMappingService));
 }
コード例 #49
0
 public FacebookPostConfigureOptions(IDataProtectionProvider dataProtection) : base(dataProtection)
 {
 }
コード例 #50
0
 public ServerComponentSerializer(IDataProtectionProvider dataProtectionProvider) =>
 public DataProtectionDemoController(IDataProtectionProvider provider)
 {
     _protector = provider.CreateProtector("TestProtector");
 }
コード例 #52
0
 /// <summary>
 /// Initializes a new instance of <see cref="PostConfigureCookieAuthenticationOptions"/>.
 /// </summary>
 /// <param name="dataProtection">The <see cref="IDataProtectionProvider"/>.</param>
 public PostConfigureCookieAuthenticationOptions(IDataProtectionProvider dataProtection)
 {
     _dp = dataProtection;
 }
コード例 #53
0
 public ApplicationUserManager(IUserStore <IdentityUser, Guid> store, IDataProtectionProvider dataProtectionProvider)
     : base(store)
 {
     Configure(dataProtectionProvider);
 }
コード例 #54
0
 public CasPostConfigureOptions(IDataProtectionProvider dataProtection)
 {
     _dataProtection = dataProtection;
 }
コード例 #55
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="next">初始化构造传入的对象</param>
 public UPSecurityMiddleware(RequestDelegate next, IDataProtectionProvider dataProtection)
 {
     this.next           = next;
     this._dataProtector = dataProtection.CreateProtector("defaultProtector");;
 }
コード例 #56
0
 public GbvController(rmsContext context, IDataProtectionProvider dataProtectionProvider, ICipherService crypto)
 {
     _context = context;
     _crypto  = crypto;
 }
コード例 #57
0
        /// <summary>
        /// Initializes a <see cref="TwitterMiddleware"/>
        /// </summary>
        /// <param name="next">The next middleware in the HTTP pipeline to invoke</param>
        /// <param name="dataProtectionProvider"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="encoder"></param>
        /// <param name="sharedOptions"></param>
        /// <param name="options">Configuration options for the middleware</param>
        public TwitterMiddleware(
            RequestDelegate next,
            IDataProtectionProvider dataProtectionProvider,
            ILoggerFactory loggerFactory,
            UrlEncoder encoder,
            IOptions <SharedAuthenticationOptions> sharedOptions,
            IOptions <TwitterOptions> options)
            : base(next, options, loggerFactory, encoder)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

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

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

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

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

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

            if (string.IsNullOrEmpty(Options.ConsumerSecret))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.ConsumerSecret)));
            }
            if (string.IsNullOrEmpty(Options.ConsumerKey))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.ConsumerKey)));
            }
            if (!Options.CallbackPath.HasValue)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.CallbackPath)));
            }

            if (Options.Events == null)
            {
                Options.Events = new TwitterEvents();
            }
            if (Options.StateDataFormat == null)
            {
                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(TwitterMiddleware).FullName, Options.AuthenticationScheme, "v1");
                Options.StateDataFormat = new SecureDataFormat <RequestToken>(
                    new RequestTokenSerializer(),
                    dataProtector);
            }

            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                Options.SignInScheme = sharedOptions.Value.SignInScheme;
            }
            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "SignInScheme"));
            }

            _httpClient         = new HttpClient(Options.BackchannelHttpHandler ?? new HttpClientHandler());
            _httpClient.Timeout = Options.BackchannelTimeout;
            _httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
            _httpClient.DefaultRequestHeaders.Accept.ParseAdd("*/*");
            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft ASP.NET Core Twitter middleware");
            _httpClient.DefaultRequestHeaders.ExpectContinue = false;
        }
コード例 #58
0
 public ContatosController(EmpresaDbContext context, IDataProtectionProvider protectionProvider, IConfiguration configuration)
 {
     _context           = context;
     _protectorProvider = protectionProvider.CreateProtector(configuration.GetSection("ChaveCriptografia").Value);
 }
コード例 #59
0
 public DefaultAntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider)
 {
     _cryptoSystem = provider.CreateProtector(Purpose);
 }
コード例 #60
0
 public DefaultDashboardController(DashboardConfigurator configurator, IDataProtectionProvider dataProtectionProvider = null)
     : base(configurator, dataProtectionProvider)
 {
 }