Esempio n. 1
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864

        // Configure the UserManager
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // 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"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(0),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            // 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();
        }
Esempio n. 2
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // 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))

                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(0),
                        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 = ""
            //});
        }
        public static void EnableCookieAuthentication(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Accounts/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))

                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(0),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
        }
Esempio n. 4
0
        public void ConfigureAuth(IAppBuilder app)
        {
            /// Configurando as Intancias do Idenity no momento em que a aplicacao
            /// for iniciada. ** Note que e necessario esta funcionalidade para que
            /// o Identity funcione na Aplicacao.
            app.CreatePerOwinContext(IdentityContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            /// Configurando o modo de autenticacao usada pelo Identity
            /// ** Note que no 'provider' usado o validateInterval para ser
            /// validado a cada request, garantindo caso houver uma mudança
            /// de permissao ou senha do usuario seja aplicada na proxima
            /// requisicao do usuario.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(StringContantsWebsite.URI_LOGIN),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(10),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                    OnApplyRedirect = context =>
                    {
                        /// Verificando se deve ser redirecionado o contexto caso não seja via WebApi
                        if (!context.Request.Path.StartsWithSegments(new PathString("/" + StringContantsWebsite.URI_WEBAPI)))
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                    }
                }
            });
        }
Esempio n. 5
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the user manager 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))

                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(0),
                        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: "SEU ID",
            //    clientSecret: "SEU TOKEN");

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

            //app.UseGoogleAuthentication(
            //    clientId: "SEU ID",
            //    clientSecret: "SEU TOKEN");

            var face = new FacebookAuthenticationOptions
            {
                AppId     = "SEU ID",
                AppSecret = "SEU TOKEN"
            };

            face.Scope.Add("email");
            face.Scope.Add("publish_actions");
            face.Scope.Add("basic_info");

            face.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = (context) =>
                {
                    context.Identity.AddClaim(new Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                    foreach (var x in context.User)
                    {
                        var    claimType  = string.Format("urn:facebook:{0}", x.Key);
                        string claimValue = x.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new Claim(claimType, claimValue, XmlSchemaString, "Facebook"));
                        }
                    }
                    return(Task.FromResult(0));
                }
            };

            face.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(face);
        }
Esempio n. 6
0
        public void Configuration(IAppBuilder app)
        {
            var config = System.Web.Http.GlobalConfiguration.Configuration;

            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling =
                Newtonsoft.Json.NullValueHandling.Ignore;
            config.CacheOutputConfiguration().RegisterCacheOutputProvider(() => new CustomCacheProvider());
            config.CacheOutputConfiguration().RegisterDefaultCacheKeyGeneratorProvider(() => new CustomCacheKeyGenerator());
            ConfigureServices(app, config);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling =
                Newtonsoft.Json.NullValueHandling.Ignore;
            app.CreatePerOwinContext(MiniSessionManager.Create);
            app.CreatePerOwinContext <UserManager>(UserManager.Create);
            app.CreatePerOwinContext(() =>
            {
                var signInManager = new SignInManager <IdentityUser, string>(
                    HttpContext.Current.GetOwinContext().GetUserManager <UserManager>(),
                    HttpContext.Current.GetOwinContext().Authentication
                    );
                return(signInManager);
            });
            System.Web.Http.GlobalConfiguration.Configure(ThrottleConfig.Register);
            System.Web.Http.GlobalConfiguration.Configure(APIRegistryConfig.Register);
            int cookieValidationIntervalInSeconds = 1;

            try
            {
                cookieValidationIntervalInSeconds = int.Parse(ConfigurationManager.AppSettings["AuthenticationCookieValidationIntervalInSeconds"]);
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("CookieValidationInterval").Error("Could not parse Cookie Validation Interval Setting! Using default...", e);
            }
            // Retrieve Session Storage cache settings, to sync with authentication cookie
            var authenticationCookineExpirationTimeout = TimeSpan.FromMinutes(20);

            //var authenticationCookineSlidingExpiration = true;
            try
            {
                var cacheConfig        = CacheFactory.FromConfiguration <object>(CacheManager.Core.ConfigurationBuilder.LoadConfiguration("SessionStateStorage"));
                var sessionCacheHandle = cacheConfig.CacheHandles.FirstOrDefault();
                authenticationCookineExpirationTimeout = sessionCacheHandle.Configuration.ExpirationTimeout;
                //authenticationCookineSlidingExpiration = sessionCacheHandle.Configuration.ExpirationMode == ExpirationMode.Sliding;
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("SessionStateStorage").Error("Could not retrieve cache configuration for Session Storage!", e);
            }
            log4net.LogManager.GetLogger("AuthenticationCookie").Info($"Authentication Cookie Timeout: {authenticationCookineExpirationTimeout.Minutes} minute(s)");
            //log4net.LogManager.GetLogger("AuthenticationCookie").Info($"Authentication Cookie Sliding Expiration Enabled: {authenticationCookineSlidingExpiration}");
            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
            {
                CookieName         = ConfigurationManager.AppSettings["AuthenticationCookieName"],
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ExpireTimeSpan     = authenticationCookineExpirationTimeout,
                //SlidingExpiration = authenticationCookineSlidingExpiration,  // Sliding expiration is always what happens despite this setting

                LoginPath = new PathString("/SignInPage/Load"),

                ReturnUrlParameter = "returnUrl",

                Provider = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = context =>
                    {
                        log4net.LogManager.GetLogger("CookieAuthenticationProvider").Error("REDIRECTING!!!");
                    },
                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(validateInterval: TimeSpan.FromSeconds(cookieValidationIntervalInSeconds)),
                    OnException        = context => log4net.LogManager.GetLogger("IdentityLogger").DebugFormat("CookieAuthenticationProvider Error for req: {0}", context.Request.Path)
                },
            });
            app.UseBasicAuthentication(new BasicAuthenticationOptions("", (id, secret) =>
            {
                try
                {
                    if (!IdentityHelper.ValidateUser(id, secret))
                    {
                        return(Task.FromResult <IEnumerable <Claim> >(null));
                    }
                    var user = IdentityHelper.GetUserManager().FindByName(id);
                    if (user == null)
                    {
                        return(Task.FromResult <IEnumerable <Claim> >(new List <Claim>()));
                    }
                    var claims = user.User.Permissions.Select(p => new Claim(ClaimTypes.Permission, p.Name)).ToList();
                    claims.Add(new Claim(System.Security.Claims.ClaimTypes.Name, user.UserName));
                    if (!string.IsNullOrWhiteSpace(user.User.Email))
                    {
                        claims.Add(new Claim(System.Security.Claims.ClaimTypes.Email, user.User.Email));
                    }
                    var userRoles = user.User.Roles.Select(r => new Claim(System.Security.Claims.ClaimTypes.Role, r.Name));
                    claims.AddRange(userRoles);
                    return(Task.FromResult <IEnumerable <Claim> >(claims));
                }
                catch (Exception e)
                {
                    log4net.LogManager.GetLogger("BasicAuthentication.CredentialValidationFunction").Error("Error validating identity!", e);
                    return(Task.FromResult <IEnumerable <Claim> >(null));
                }
            }));
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:authority"]))
            {
                var options = new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = ConfigurationManager.AppSettings["idsrv:authority"]
                };
                if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:scopes"]))
                {
                    options.RequiredScopes = ConfigurationManager.AppSettings["idsrv:scopes"].Split(' ');
                }
                if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:clientid"]) &&
                    !string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:clientsecret"]))
                {
                    options.ClientId     = ConfigurationManager.AppSettings["idsrv:clientid"];
                    options.ClientSecret = ConfigurationManager.AppSettings["idsrv:clientsecret"];
                }
                app.UseIdentityServerBearerTokenAuthentication(options);
            }
            else
            {
                // Configure the application for OAuth based flow
                var PublicClientId = "self";
                var OAuthOptions   = new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath         = new PathString("/OAuth/Token"),
                    Provider                  = new zAppDev.DotNet.Framework.Identity.AppOAuthProvider(PublicClientId),
                    AuthorizeEndpointPath     = new PathString("/OAuth/Account/ExternalLogin"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
                    AllowInsecureHttp         = true // Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!
                };
                // Enable the application to use bearer tokens to authenticate users
                app.UseOAuthBearerTokens(OAuthOptions);
            }
            Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver.Register(typeof(Newtonsoft.Json.JsonSerializer), () =>
            {
                return(Newtonsoft.Json.JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    ContractResolver = new zAppDev.DotNet.Framework.Utilities.NHibernateContractResolver()
                }));
            });
            app.MapSignalR();
            zAppDev.DotNet.Framework.Identity.IdentityHelper.AllowMultipleSessionsPerUser = true;
            zAppDev.DotNet.Framework.Identity.IdentityHelper.AdminCanResetPassword        = false;
            DSS3_LogisticsPoolingForUrbanDistribution.DatabaseSeeder databaseSeeder = new DSS3_LogisticsPoolingForUrbanDistribution.DatabaseSeeder();
            databaseSeeder.UpdateAuthorizationTables();
            ConfigeAuditTrailManager();
            ServiceLocator.Current.GetInstance <zAppDev.DotNet.Framework.Workflow.ScheduleManager>();
            ServiceLocator.Current.GetInstance <zAppDev.DotNet.Framework.Workflow.WorkflowManager>()
            .Init(typeof(DSS3_LogisticsPoolingForUrbanDistribution.DAL.Repository).Assembly);
            DSS3_LogisticsPoolingForUrbanDistribution.Hubs.EventsHub.RaiseApplicationStart();
            zAppDev.DotNet.Framework.Mvc.FileHelper.ClearTempData();
        }