Esempio n. 1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDistributedMemoryCache();
            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddSession();
            var mvcBuilder = services.AddMvc(
                options =>
            {
                options.Filters.Add(new HandleErrorExAttribute());
                options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
                options.Filters.Add(new CheckContextAttributes());
                if (Parameters.Service.RequireHttps)
                {
                    options.Filters.Add(new Microsoft.AspNetCore.Mvc.RequireHttpsAttribute());
                }
            });

            if (Authentications.SAML())
            {
                services
                .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => o.LoginPath = new PathString("/users/login"))
                .AddSaml2(options =>
                {
                    Saml.SetSPOptions(options);
                });
            }
            else
            {
                services
                .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => o.LoginPath = new PathString("/users/login"));
            }
            var extensionDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ExtendedLibraries");

            if (Directory.Exists(extensionDirectory))
            {
                foreach (var assembly in Directory.GetFiles(extensionDirectory, "*.dll").Select(dll => Assembly.LoadFrom(dll)).ToArray())
                {
                    mvcBuilder.AddApplicationPart(assembly);
                }
            }
            services.Configure <FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = int.MaxValue;
            });
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
                options.MaxRequestBodySize = long.MaxValue;
            });
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO        = true;
                options.Limits.MaxRequestBodySize = long.MaxValue;
            })
            .Configure <KestrelServerOptions>(configuration.GetSection("Kestrel"));
            services.AddHealthChecks();
        }
 /// <summary>
 /// Constructor loading group attributes from a Saml.Response
 /// </summary>
 /// <param name="samlResponse"></param>
 public Membership(Saml.Response samlResponse)
 {
     NameValueCollection att = samlResponse.GetAttributes();
     UserUid = att["uid"];
     GroupUid = att["group_uid"];
     Role = att["group_role"];
 }
 private void SetConfigrations(Context context)
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     GlobalConfiguration.Configure(ApiRouteConfig.Register);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     ViewEngines.Engines.Clear();
     ViewEngines.Engines.Add(new RazorViewEngine());
     Saml.RegisterSamlConfiguration(context: context);
 }
        /// <summary>
        /// Fixed:
        /// </summary>
        public (string redirectUrl, string redirectResultUrl, string html) Login(
            Context context, string returnUrl, bool isLocalUrl, string ssocode = "")
        {
            var log = new SysLogModel(context: context);

            if (context.Authenticated)
            {
                if (context.QueryStrings.Bool("new"))
                {
                    Authentications.SignOut(context: context);
                }
                log.Finish(context: context);
                return(isLocalUrl
                    ? returnUrl
                    : Locations.Top(context: context), null, null);
            }
            if ((Parameters.Authentication.Provider == "SAML-MultiTenant") && (ssocode != string.Empty))
            {
                var tenant = new TenantModel().Get(
                    context: context,
                    ss: SiteSettingsUtilities.TenantsSiteSettings(context),
                    where : Rds.TenantsWhere().Comments(ssocode));
                if (tenant.AccessStatus == Databases.AccessStatuses.Selected)
                {
                    var redirectUrl = Saml.SetIdpConfiguration(context, tenant.TenantId);
                    if (redirectUrl != null)
                    {
                        return(null, redirectUrl, null);
                    }
                }
                return(null, Locations.InvalidSsoCode(context), null);
            }
            var html = UserUtilities.HtmlLogin(
                context: context,
                returnUrl: isLocalUrl
                    ? returnUrl
                    : string.Empty,
                message: context.QueryStrings.ContainsKey("expired") && context.QueryStrings["expired"] == "1" && !context.Ajax
                    ? Messages.Expired(context: context).Text
                    : string.Empty);

            log.Finish(context: context, responseSize: html.Length);
            return(null, null, html);
        }
        public ActionResult Login(string returnUrl, string ssocode = "")
        {
            var context = new Context();
            var log     = new SysLogModel(context: context);

            if ((Parameters.Authentication.Provider == "SAML-MultiTenant") && (ssocode != string.Empty))
            {
                var tenant = new TenantModel().Get(
                    context: context,
                    ss: SiteSettingsUtilities.TenantsSiteSettings(context),
                    where : Rds.TenantsWhere().Comments(ssocode));
                if (tenant.AccessStatus == Databases.AccessStatuses.Selected)
                {
                    Authentications.SignOut(context: context);
                    var redirectUrl = Saml.SetIdpConfiguration(context, tenant.TenantId);
                    if (redirectUrl != null)
                    {
                        return(new RedirectResult(redirectUrl));
                    }
                }
                return(new RedirectResult(Locations.InvalidSsoCode(context)));
            }
            if (context.Authenticated)
            {
                if (context.QueryStrings.Bool("new"))
                {
                    Authentications.SignOut(context: context);
                }
                log.Finish(context: context);
                return(base.Redirect(Url.IsLocalUrl(returnUrl)
                    ? returnUrl
                    : Locations.Top(context: context)));
            }
            var html = UserUtilities.HtmlLogin(
                context: context,
                returnUrl: Url.IsLocalUrl(returnUrl) ? returnUrl : "",
                message: Request.QueryString["expired"] == "1" && !Request.IsAjaxRequest()
                    ? Messages.Expired(context: context).Text
                    : string.Empty);

            ViewBag.HtmlBody = html;
            log.Finish(context: context, responseSize: html.Length);
            return(View());
        }
        /// <summary>
        /// Fixed:
        /// </summary>
        public ActionResult SamlLogin()
        {
            var context = new Context();

            if (HttpContext.User?.Identity?.AuthenticationType == "Federation" &&
                HttpContext.User?.Identity?.IsAuthenticated == true)
            {
                Authentications.SignOut();
                var loginId       = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier);
                var firstName     = string.Empty;
                var lastName      = string.Empty;
                var tenantManager = false;
                foreach (var claim in ClaimsPrincipal.Current.Claims)
                {
                    switch (claim.Type)
                    {
                    case "FirstName":
                        firstName = claim.Value;
                        break;

                    case "LastName":
                        lastName = claim.Value;
                        break;

                    case "TenantManager":
                        tenantManager = claim.Value.ToLower() == "true" ? true : false;
                        break;
                    }
                }
                var space = (string.IsNullOrEmpty(lastName) || string.IsNullOrEmpty(firstName)) ? string.Empty : " ";
                var name  = lastName + space + firstName;
                if (name == string.Empty)
                {
                    return(new RedirectResult(Locations.EmptyUserName(context: context)));
                }
                var ssocode = loginId.Issuer.TrimEnd('/').Substring(loginId.Issuer.TrimEnd('/').LastIndexOf('/') + 1);
                var tenant  = new TenantModel().Get(
                    context: context,
                    ss: SiteSettingsUtilities.TenantsSiteSettings(context),
                    where : Rds.TenantsWhere().Comments(ssocode));
                try
                {
                    Saml.UpdateOrInsert(
                        context: context,
                        tenantId: tenant.TenantId,
                        loginId: loginId.Value,
                        name: name,
                        mailAddress: loginId.Value,
                        tenantManager: tenantManager,
                        synchronizedTime: System.DateTime.Now);
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    if (e.Number == 2601)
                    {
                        return(new RedirectResult(Locations.LoginIdAlreadyUse(context: context)));
                    }
                    throw;
                }
                var user = new UserModel().Get(
                    context: context,
                    ss: null,
                    where : Rds.UsersWhere()
                    .TenantId(tenant.TenantId)
                    .LoginId(loginId.Value));
                if (user.AccessStatus == Databases.AccessStatuses.Selected)
                {
                    if (user.Disabled)
                    {
                        return(new RedirectResult(Locations.UserDisabled(context: context)));
                    }
                    if (user.Lockout)
                    {
                        return(new RedirectResult(Locations.UserLockout(context: context)));
                    }
                    user.Allow(context: context, returnUrl: Locations.Top(context), createPersistentCookie: true);
                    return(new RedirectResult(Locations.Top(context)));
                }
                else
                {
                    return(new RedirectResult(Locations.SamlLoginFailed(context: context)));
                }
            }
            return(new RedirectResult(Locations.SamlLoginFailed(context: context)));
        }
Esempio n. 7
0
        /// <summary>
        /// Fixed:
        /// </summary>
        public (string redirectUrl, string redirectResultUrl, string html) SamlLogin(Context context)
        {
            if (!Authentications.SAML() ||
                context.AuthenticationType != "Federation" ||
                context.IsAuthenticated != true)
            {
                return(null, Locations.SamlLoginFailed(context: context), null);
            }
            Authentications.SignOut(context: context);
            var         loginId    = context.UserClaims?.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier);
            var         attributes = Saml.MapAttributes(context.UserClaims, loginId.Value);
            var         name       = attributes.UserName;
            TenantModel tenant;

            if (Parameters.Authentication.Provider == "SAML-MultiTenant")
            {
                if (string.IsNullOrEmpty(name))
                {
                    return(null, Locations.EmptyUserName(context: context), null);
                }
                var ssocode = loginId.Issuer.TrimEnd('/').Substring(loginId.Issuer.TrimEnd('/').LastIndexOf('/') + 1);
                tenant = new TenantModel().Get(
                    context: context,
                    ss: SiteSettingsUtilities.TenantsSiteSettings(context),
                    where : Rds.TenantsWhere().Comments(ssocode));
            }
            else
            {
                tenant = new TenantModel().Get(
                    context: context,
                    ss: SiteSettingsUtilities.TenantsSiteSettings(context),
                    where : Rds.TenantsWhere().TenantId(Parameters.Authentication.SamlParameters.SamlTenantId));
                if (tenant.AccessStatus != Databases.AccessStatuses.Selected)
                {
                    Rds.ExecuteNonQuery(
                        context: context,
                        connectionString: Parameters.Rds.OwnerConnectionString,
                        statements: new[] {
                        Rds.IdentityInsertTenants(factory: context, on: true),
                        Rds.InsertTenants(
                            param: Rds.TenantsParam()
                            .TenantId(Parameters.Authentication.SamlParameters.SamlTenantId)
                            .TenantName("DefaultTenant")),
                        Rds.IdentityInsertTenants(factory: context, on: false)
                    });
                    tenant.TenantId = Parameters.Authentication.SamlParameters.SamlTenantId;
                }
            }
            try
            {
                Saml.UpdateOrInsert(
                    context: context,
                    tenantId: tenant.TenantId,
                    loginId: loginId.Value,
                    name: string.IsNullOrEmpty(name)
                        ? loginId.Value
                        : name,
                    mailAddress: attributes["MailAddress"],
                    synchronizedTime: System.DateTime.Now,
                    attributes: attributes);
            }
            catch (DbException e)
            {
                if (context.SqlErrors.ErrorCode(e) == 2601)
                {
                    return(null, Locations.LoginIdAlreadyUse(context: context), null);
                }
                throw;
            }
            var user = new UserModel().Get(
                context: context,
                ss: null,
                where : Rds.UsersWhere()
                .TenantId(tenant.TenantId)
                .LoginId(loginId.Value));

            if (user.AccessStatus == Databases.AccessStatuses.Selected)
            {
                if (user.Disabled)
                {
                    return(null, Locations.UserDisabled(context: context), null);
                }
                if (user.Lockout)
                {
                    return(null, Locations.UserLockout(context: context), null);
                }
                user.Allow(context: context, returnUrl: Locations.Top(context), createPersistentCookie: true);
                return(null, Locations.Top(context), null);
            }
            else
            {
                return(null, Locations.SamlLoginFailed(context: context), null);
            }
        }
Esempio n. 8
0
 private void SetConfigrations(Context context)
 {
     Saml.RegisterSamlConfiguration(context: context);
 }
Esempio n. 9
0
 /// <summary>
 /// Constructor loading user attributes from a Saml.Response
 /// </summary>
 /// <param name="samlResponse"></param>
 public User(Saml.Response samlResponse = null)
 {
     this.New(samlResponse);
 }
Esempio n. 10
0
        /// <summary>
        /// Initialize a new User
        /// </summary>
        /// <returns></returns>
        public User New(Saml.Response samlResponse)
        {
            if (samlResponse != null)
            {
                NameValueCollection att = samlResponse.GetAttributes();
                SsoSession = att["mno_session"];
                SsoSessionRecheck = DateTime.Parse(att["mno_session_recheck"]);
                GroupUid = att["group_uid"];
                GroupRole = att["group_role"];
                Uid = att["uid"];
                VirtualUid = att["virtual_uid"];
                Email = att["email"];
                VirtualEmail = att["virtual_email"];
                FirstName = att["name"];
                LastName = att["surname"];
                Country = att["country"];
                CompanyName = att["company_name"];
            }

            return this;
        }
Esempio n. 11
0
 /// <summary>
 /// Constructor loading group attributes from a Saml.Response
 /// </summary>
 /// <param name="samlResponse"></param>
 public Group(Saml.Response samlResponse = null)
 {
     this.New(samlResponse);
 }
Esempio n. 12
0
        /// <summary>
        /// Initialize the Group
        /// </summary>
        /// <returns></returns>
        public Group New(Saml.Response samlResponse)
        {
            if (samlResponse != null)
            {
                NameValueCollection att = samlResponse.GetAttributes();

                // General info
                Uid = att["group_uid"];
                Name = att["group_name"];
                Email = att["group_email"];
                CompanyName = att["company_name"];
                HasCreditCard = att["group_has_credit_card"].Equals("true");

                // Set Free trial in the past on failure
                try
                {
                    FreeTrialEndAt = DateTime.Parse(att["group_end_free_trial"]);
                }
                catch
                {
                    FreeTrialEndAt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                }

                // Geo info
                Currency = att["group_currency"];
                Timezone = TimeZoneConverter.fromOlsonTz(att["group_timezone"]);
                Country = att["group_country"];
                City = att["group_city"];
            }

            return this;
        }