Example #1
0
        public static IdentityConfiguration GetConfig()
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("config.json", reloadOnChange: true, optional: false);

            var root = configuration.Build();

            var idconfig = new IdentityConfiguration()
            {
                Uri                = root["IdentityCosmosDB:identityConfiguration:uri"],
                AuthKey            = root["IdentityCosmosDB:identityConfiguration:authKey"],
                Database           = root["IdentityCosmosDB:identityConfiguration:database"],
                IdentityCollection = root["IdentityCosmosDB:identityConfiguration:identityCollection"],
                Options            = new CosmosClientOptions()
                {
                    ConnectionMode    = ConnectionMode.Gateway,
                    ConsistencyLevel  = ConsistencyLevel.Session,
                    SerializerOptions = new CosmosSerializationOptions()
                }
            };

            idconfig.Options.SerializerOptions.PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase;

            return(idconfig);
        }
Example #2
0
        private static ReadOnlyCollection <ClaimsIdentity> ValidateToken(string token)
        {
            using (var stringReader = new StringReader(token))
            {
                using (var reader = XmlReader.Create(stringReader))
                {
                    var serviceConfiguration = new IdentityConfiguration(true)
                    {
                        CertificateValidator = X509CertificateValidator.None,
                        SaveBootstrapContext = true
                    };

                    foreach (var securityTokenHandler in serviceConfiguration.SecurityTokenHandlers)
                    {
                        if (securityTokenHandler.GetType().Name == "Saml11SecurityTokenHandler")
                        {
                            var samlToken = securityTokenHandler.ReadToken(reader);
                            return(securityTokenHandler.ValidateToken(samlToken));
                        }
                    }
                }
            }

            throw new Exception("Could not find Saml11SecurityTokenHandler");
        }
Example #3
0
        public static IServiceCollection AddIdentityContext(this IServiceCollection services)
        {
            var config = new IdentityConfiguration();

            services.AddDbContext <IdentityContext>(options =>
            {
                options.UseSqlServer(config.ConnectionString);
            });

            services.AddIdentity <User, Role>(configs =>
            {
                configs.User.RequireUniqueEmail = true;
                configs.Password = new PasswordOptions
                {
                    RequireDigit           = false,
                    RequireLowercase       = false,
                    RequireNonAlphanumeric = false,
                    RequireUppercase       = false,
                    RequiredLength         = 5
                };
            })
            .AddEntityFrameworkStores <IdentityContext>()
            .AddDefaultTokenProviders();

            return(services);
        }
Example #4
0
        private ClaimsPrincipal AuthenticateToken(SecurityToken token, string resourceName)
        {
            IdentityConfiguration identityConfiguration = _federationConfiguration.IdentityConfiguration;
            var incomingPrincipal = new ClaimsPrincipal(identityConfiguration.SecurityTokenHandlers.ValidateToken(token));

            return(identityConfiguration.ClaimsAuthenticationManager.Authenticate(resourceName, incomingPrincipal));
        }
        protected override void ValidateTestCase(string testCase)
        {
            IdentityConfiguration identityConfig = new IdentityConfiguration(IdentityConfiguration.DefaultServiceName);

            JwtSecurityTokenHandler jwtHandler = identityConfig.SecurityTokenHandlers[typeof(JwtSecurityToken)] as JwtSecurityTokenHandler;

            jwtHandler.RequireExpirationTime = false;
            Assert.IsNotNull(jwtHandler);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor()
            {
                TokenIssuerName    = "https://wiftooling.accesscontrol.windows.net",
                AppliesToAddress   = "http://localhost",
                SigningCredentials = KeyingMaterial.X509SigningCreds_2048_RsaSha2_Sha2,
            };

            try
            {
                SecurityToken        jwtToken    = jwtHandler.CreateToken(tokenDescriptor);
                string               tokenString = jwtHandler.WriteToken(jwtToken);
                List <SecurityToken> tokens      = new List <SecurityToken>(KeyingMaterial.AsymmetricTokens);
                jwtHandler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true);
                jwtToken = jwtHandler.ReadToken(tokenString);
                jwtHandler.CertificateValidator             = X509CertificateValidator.None;
                jwtHandler.Configuration.IssuerNameRegistry = new  SetNameIssuerNameRegistry("https://wiftooling.accesscontrol.windows.net");
                ClaimsPrincipal cp = new ClaimsPrincipal(jwtHandler.ValidateToken(jwtToken));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddDbContext<ApplicationDbContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add Elcamino Azure Table Identity services.

            services.AddIdentity <ApplicationUser, ElCamino.AspNetCore.Identity.AzureTable.Model.IdentityRole>((options) =>
            {
                options.User.RequireUniqueEmail = true;
            })
            .AddAzureTableStores <ApplicationDbContext>(new Func <IdentityConfiguration>(() =>
            {
                IdentityConfiguration idconfig   = new IdentityConfiguration();
                idconfig.TablePrefix             = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:TablePrefix").Value;
                idconfig.StorageConnectionString = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:StorageConnectionString").Value;
                idconfig.LocationMode            = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:LocationMode").Value;
                return(idconfig);
            }))
            .AddDefaultTokenProviders()
            .CreateAzureTablesIfNotExists <ApplicationDbContext>();    //can remove after first run;
            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc();
        }
 public static void Register(IServiceCollection services)
 {
     RepositoryServices.Register(services);
     MapperServices.Register(services);
     ApplicationServices.Register(services);
     IdentityConfiguration.Register(services);
 }
Example #8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     //services.AddDbContext<ApplicationDbContext>(options =>
     //    options.UseSqlServer(
     //        Configuration.GetConnectionString("DefaultConnection")));
     services.AddDefaultIdentity <IdentityUser>(options =>
     {
         options.SignIn.RequireConfirmedAccount = true;
         options.User.RequireUniqueEmail        = true;
     })
     //ElCamino configuration
     .AddAzureTableStores <ApplicationDbContext>(new Func <IdentityConfiguration>(() =>
     {
         IdentityConfiguration idconfig   = new IdentityConfiguration();
         idconfig.TablePrefix             = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:TablePrefix").Value;
         idconfig.StorageConnectionString = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:StorageConnectionString").Value;
         idconfig.LocationMode            = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:LocationMode").Value;
         idconfig.IndexTableName          = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:IndexTableName").Value; // default: AspNetIndex
         idconfig.RoleTableName           = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:RoleTableName").Value;  // default: AspNetRoles
         idconfig.UserTableName           = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:UserTableName").Value;  // default: AspNetUsers
         return(idconfig);
     }))
     .AddDefaultTokenProviders()
     .AddDefaultUI()
     .CreateAzureTablesIfNotExists <ApplicationDbContext>(); //can remove after first run;
     //.AddEntityFrameworkStores<ApplicationDbContext>();
     services.AddControllersWithViews();
     services.AddRazorPages();
 }
Example #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <Context>(options =>
                                            options.UseSqlServer(Configuration.GetConnectionString("Connection")));

            IdentityConfiguration.AddIdentity(services);
            services.AddCors();
            services.AddMvc();


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <UrlResolver>();
            IdentityConfiguration.ConfigureIdentity(services);

            services.AddSingleton(_ => Configuration as IConfigurationRoot);
            services.AddScoped <PasswordHasher <User> >();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IEventRepository, EventRepository>();
            services.AddScoped <IEventService, EventService>();
            services.AddScoped <IStatusService, StatusService>();
            services.AddScoped <IStatusRepository, StatusRepository>();
            services.AddScoped <ICommentRepository, CommentRepository>();
            services.AddScoped <ICommentService, CommentService>();
            services.AddScoped <IUserService, UserService>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "CoolMeet API", Version = "v1"
                });
            });
            services.AddAutoMapper();

            JwtConfiguration.AddJwtAuthorization(Configuration, services);
        }
Example #10
0
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            // Pretend this claim comes from a token minted by an STS
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, "jqhuman")
            };                                                                        // User Id of John Q Human

            var id        = new ClaimsIdentity(claims, "dummy");
            var principal = new ClaimsPrincipal(new[] { id });

            var config       = new IdentityConfiguration();
            var newPrincipal = config.ClaimsAuthenticationManager
                               .Authenticate(request.RequestUri.ToString(), principal);

            Thread.CurrentPrincipal = newPrincipal;

            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = newPrincipal;
            }

            return(await base.SendAsync(request, cancellationToken));
        }
Example #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="options"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            // See in web.config
            IdentityConfiguration identityConfiguration = (IdentityConfiguration)ConfigurationManager.GetSection("identityConfiguration");

            var manager = new ApplicationUserManager(new UserStore <User>(context.Get <AppDbContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <User>(manager)
            {
                AllowOnlyAlphanumericUserNames = identityConfiguration?.UserValidator?.AllowOnlyAlphanumericUserNames ?? UserValidatorElement.AllowOnlyAlphanumericUserNamesDefault,
                RequireUniqueEmail             = identityConfiguration?.UserValidator?.RequireUniqueEmail ?? UserValidatorElement.RequireUniqueEmailDefault
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = identityConfiguration?.PasswordValidator?.RequiredLength ?? PasswordValidatorElement.RequiredLengthDefault,
                RequireNonLetterOrDigit = identityConfiguration?.PasswordValidator?.RequireNonLetterOrDigit ?? PasswordValidatorElement.RequireNonLetterOrDigitDefault,
                RequireDigit            = identityConfiguration?.PasswordValidator?.RequireDigit ?? PasswordValidatorElement.RequireDigitDefault,
                RequireLowercase        = identityConfiguration?.PasswordValidator?.RequireLowercase ?? PasswordValidatorElement.RequireLowercaseDefault,
                RequireUppercase        = identityConfiguration?.PasswordValidator?.RequireUppercase ?? PasswordValidatorElement.RequireUppercaseDefault,
            };

            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <User>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Example #12
0
        public static void PreAppStart()
        {
            FederatedAuthentication.FederationConfigurationCreated += (sender, args) =>
            {
                // Load config
                var audience   = ConfigurationManager.AppSettings["Auth.AudienceUrl"];
                var realm      = ConfigurationManager.AppSettings["Auth.AuthenticationRealm"];
                var issuer     = ConfigurationManager.AppSettings["Auth.AuthenticationIssuer"];
                var thumbprint = ConfigurationManager.AppSettings["Auth.AuthenticationIssuerThumbprint"];

                var idconfig = new IdentityConfiguration();
                idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience));

                var registry = new ConfigurationBasedIssuerNameRegistry();
                registry.AddTrustedIssuer(thumbprint, issuer);
                idconfig.IssuerNameRegistry = registry;

                var sessionTransforms = new List <CookieTransform>()
                {
                    new DeflateCookieTransform(),
                    new MachineKeyTransform()
                };
                idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly()));

                var wsfedconfig = new WsFederationConfiguration(issuer, realm);
                wsfedconfig.PersistentCookiesOnPassiveRedirects = true;
                wsfedconfig.PassiveRedirectEnabled = true;

                args.FederationConfiguration.IdentityConfiguration     = idconfig;
                args.FederationConfiguration.WsFederationConfiguration = wsfedconfig;
                args.FederationConfiguration.CookieHandler             = new ChunkedCookieHandler();
            };
        }
Example #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <IdentitySettings>(Configuration);
            var settings = Configuration.Get <IdentitySettings>();

            services.AddSingleton(settings);

            services.AddIdentityServer
            (
                options =>
            {
                options.IssuerUri = settings.IdentityEndPoint;
                options.Endpoints.EnableDiscoveryEndpoint = true;
                options.Endpoints.EnableTokenEndpoint     = true;
                options.Endpoints.EnableUserInfoEndpoint  = true;

                options.Endpoints.EnableAuthorizeEndpoint       = false;
                options.Endpoints.EnableCheckSessionEndpoint    = false;
                options.Endpoints.EnableEndSessionEndpoint      = false;
                options.Endpoints.EnableIntrospectionEndpoint   = false;
                options.Endpoints.EnableTokenRevocationEndpoint = false;
            }
            )
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityConfiguration.GetApiResources(settings))
            .AddInMemoryClients(IdentityConfiguration.GetClients(settings));

            services.AddMvc();
        }
Example #14
0
        public void Initialize()
        {
            var config = new HttpSelfHostConfiguration(BaseAddress);

            //SecurityConfig.ConfigureGlobal(config);

            config.Routes.MapHttpRoute(
                "ControllerActionId",
                "{controller}/{action}/{id}");
            config.Routes.MapHttpRoute(
                "ControllerId",
                "{controller}/{id}");
            config.Routes.MapHttpRoute(
                "ControllerOnly",
                "{controller}",
                new { action = "DefaultAction" });

            var ic           = new IdentityConfiguration();
            var realm        = ic.AudienceRestriction.AllowedAudienceUris.FirstOrDefault();
            var issuer       = ((ValidatingIssuerNameRegistry)ic.IssuerNameRegistry).IssuingAuthorities.FirstOrDefault();
            var issuerName   = issuer.Name;
            var symmetricKey = issuer.SymmetricKeys.FirstOrDefault();

            var authenticationHandler = new AuthenticationHandler
            {
                Realm        = realm.ToString(),
                IssuerName   = issuerName,
                SymmetricKey = symmetricKey
            };

            config.MessageHandlers.Add(authenticationHandler);

            Server = new HttpSelfHostServer(config);
        }
Example #15
0
        private void SetupFederatedLogin()
        {
            FederatedAuthentication.FederationConfigurationCreated += (sender, args) =>
            {
                var config   = Kernel.Get <IConfigurationService>();
                var idconfig = new IdentityConfiguration();
                idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(config.Auth.AudienceUrl));

                var registry = new ConfigurationBasedIssuerNameRegistry();
                registry.AddTrustedIssuer(config.Auth.TokenCertificateThumbprint, config.Auth.AuthenticationIssuer);
                idconfig.IssuerNameRegistry        = registry;
                idconfig.CertificateValidationMode = X509CertificateValidationMode.None;

                var sessionTransforms = new List <CookieTransform>()
                {
                    new DeflateCookieTransform(),
                    new MachineKeyTransform()
                };
                idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly()));

                var wsfedconfig = new WsFederationConfiguration(config.Auth.AuthenticationIssuer, config.Auth.AuthenticationRealm);
                wsfedconfig.PersistentCookiesOnPassiveRedirects = true;

                args.FederationConfiguration.IdentityConfiguration     = idconfig;
                args.FederationConfiguration.WsFederationConfiguration = wsfedconfig;
                args.FederationConfiguration.CookieHandler             = new ChunkedCookieHandler();
            };
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(
                options =>
                options
                .UseLazyLoadingProxies()
                .EnableSensitiveDataLogging()
                .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddControllersWithViews();

            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <MailSettings>(Configuration.GetSection("MailSettings"));

            IdentityConfiguration.ConfigureIdentity(services);
            services.AddRazorPages();
            CustomDIMappings.AddApplicationDIMappings(services);
            services.AddControllers(config =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });
        }
Example #17
0
        /// <summary>
        /// Construct the options from the given configuration section
        /// </summary>
        /// <param name="configSection"></param>
        public SPOptions(KentorAuthServicesSection configSection)
        {
            if (configSection == null)
            {
                throw new ArgumentNullException(nameof(configSection));
            }
            systemIdentityModelIdentityConfiguration = new IdentityConfiguration(true);

            ReturnUrl             = configSection.ReturnUrl;
            MetadataCacheDuration = configSection.MetadataCacheDuration;
            DiscoveryServiceUrl   = configSection.DiscoveryServiceUrl;
            EntityId     = configSection.EntityId;
            ModulePath   = configSection.ModulePath;
            Organization = configSection.Organization;
            AuthenticateRequestSigningBehavior = configSection.AuthenticateRequestSigningBehavior;
            NameIdPolicy = configSection.NameIdPolicy;

            configSection.ServiceCertificates.RegisterServiceCertificates(this);

            foreach (var acs in configSection.AttributeConsumingServices)
            {
                AttributeConsumingServices.Add(acs);
            }

            foreach (var contact in configSection.Contacts)
            {
                Contacts.Add(contact);
            }
        }
Example #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddDbContext<ApplicationDbContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add Elcamino Azure Table Identity services.

            services.AddIdentity <ApplicationUser, ElCamino.AspNetCore.Identity.AzureTable.Model.IdentityRole>((options) =>
            {
                options.User.RequireUniqueEmail = true;
            })
            //or use .AddAzureTableStores with your ApplicationUser extends IdentityUser if your code depends on the Role, Claim and Token collections on the user object.
            //You can safely switch between .AddAzureTableStores and .AddAzureTableStoresV2. Just make sure the Application User extends the correct IdentityUser/IdentityUserV2
            .AddAzureTableStoresV2 <ApplicationDbContext>(new Func <IdentityConfiguration>(() =>
            {
                IdentityConfiguration idconfig   = new IdentityConfiguration();
                idconfig.TablePrefix             = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:TablePrefix").Value;
                idconfig.StorageConnectionString = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:StorageConnectionString").Value;
                idconfig.LocationMode            = Configuration.GetSection("IdentityAzureTable:IdentityConfiguration:LocationMode").Value;
                return(idconfig);
            }))
            .AddDefaultTokenProviders()
            .CreateAzureTablesIfNotExists <ApplicationDbContext>();    //can remove after first run;
            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc();
        }
Example #19
0
 public Configuration()
 {
     UsingChannelShuffler <DefaultChannelShuffler>();
     UsingRouterInterceptor <NullRouterInterceptor>();
     UsingBusInterceptor <NullBusInterceptor>();
     UsingSagaStorage <NullSagaStorage>();
     UsingMessageStorage <NullMessageStorage>();
     UsingChannelManager <NullChannelManager>();
     UsingPointToPointChannel <NullPointToPointChannel>();
     UsingPublishSubscribeChannel <NullPublishSubscribeChannel>();
     UsingRequestReplyChannel <NullRequestReplyChannel>();
     UsingMessageSerializer <NullMessageSerializer>();
     UsingMessageAdapter <NullMessageAdapter>();
     InboundMiddlewareTypes  = new List <Type>();
     RouterLoggerTypes       = new List <Type>();
     MonitoringTaskTypes     = new List <TaskMetadata>();
     StartupTaskTypes        = new List <Type>();
     ShutdownTaskTypes       = new List <Type>();
     LoggerTypes             = new Dictionary <Type, IList <Type> >();
     OutboundMiddlewareTypes = new List <Type>();
     AddLogger <HeartBeatLogger, HeartBeat>();
     AddLogger <StartupBeatLogger, StartupBeat>();
     AddLogger <ShutdownBeatLogger, ShutdownBeat>();
     AddStartupTask <StartupTask>();
     AddStartupTask <HandlerAndEndpointStartupTask>();
     AddStartupTask <ChannelStartupTask>();
     AddStartupTask <ListenerStartupTask>();
     AddShutdownTask <ListenerShutdownTask>();
     AddShutdownTask <ShutdownTask>();
     UsingShutdownWatcher <ShutdownNullWatcher>();
     Storage             = new StorageConfiguration();
     Identity            = new IdentityConfiguration();
     ApplicationName     = "[Empty]";
     ChannelProviderName = "[Empty]";
 }
Example #20
0
        protected override void ValidateTestCase(string testVariation)
        {
            IdentityConfiguration identityConfig = new IdentityConfiguration(IdentityConfiguration.DefaultServiceName);

            Assert.IsNotNull(identityConfig.IssuerTokenResolver);

            Assert.IsFalse(identityConfig.IssuerTokenResolver.GetType() != typeof(NamedKeyIssuerTokenResolver), string.Format("Expected identityConfiguration.IsuerTokenResolver.GetType() == typeof( NamedKeyIssuerTokenResolver ), was: '{0}'", identityConfig.IssuerTokenResolver.GetType()));

            NamedKeyIssuerTokenResolver resolver = identityConfig.IssuerTokenResolver as NamedKeyIssuerTokenResolver;

            Assert.IsTrue(resolver.SecurityKeys.Count == 0);
            Assert.IsTrue(IssuerTokenResolver.DefaultStoreName == StoreName.TrustedPeople);
            Assert.IsTrue(IssuerTokenResolver.DefaultStoreLocation == StoreLocation.LocalMachine);

            // Should not find key
            SecurityKey key = null;
            NamedKeySecurityKeyIdentifierClause clause = new NamedKeySecurityKeyIdentifierClause("keyName", "KeyingMaterial.SymmetricKeyBytes_256");

            Assert.IsFalse(resolver.TryResolveSecurityKey(clause, out key));
            Assert.IsNull(key);

            // Should not find token
            SecurityToken token = null;

            Assert.IsFalse(resolver.TryResolveToken(clause, out token));
            Assert.IsNull(token);
        }
Example #21
0
 /// <summary>
 /// Ctor
 /// </summary>
 public SPOptions()
 {
     systemIdentityModelIdentityConfiguration = new IdentityConfiguration(false);
     MetadataCacheDuration = new TimeSpan(1, 0, 0);
     Compatibility         = new Compatibility();
     SigningAlgorithm      = XmlHelpers.GetDefaltSigningAlgorithmName();
 }
Example #22
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var principal = actionContext.RequestContext.Principal;
            var context   = new AuthorizationContext(principal as ClaimsPrincipal, "resource", "action");
            var claims    = new List <Claim>();

            if (Permissions == null || !Permissions.Any())
            {
                base.OnAuthorization(actionContext);
                return;
            }
            foreach (var permission in Permissions)
            {
                var claim = new Claim("http://localhost/claims/permission", permission);
                claims.Add(claim);
            }
            claims.ToList().ForEach(claim => context.Resource.Add(claim));
            var config = new IdentityConfiguration();
            var result = config.ClaimsAuthorizationManager.CheckAccess(context);

            if (!result)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return;
            }
            base.OnAuthorization(actionContext);
        }
Example #23
0
        public void AuthenticateUsingMsftJwt(string token)
        {
            try
            {
                // Use JWTSecurityTokenHandler to validate the JWT token
                JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler();

                TokenValidationParameters parms = new TokenValidationParameters()
                {
                    AllowedAudience = "MyRelyingPartApp",
                    ValidIssuers    = new List <string>()
                    {
                        "TokenIssuer"
                    },
                    SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(this.secretKey))
                };

                var config = new IdentityConfiguration();
                Thread.CurrentPrincipal = config
                                          .ClaimsAuthenticationManager
                                          .Authenticate("TheMethodRequiringAuthZ",
                                                        tokenHandler.ValidateToken(token, parms));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #24
0
        /// <summary>
        /// Construct the options from the given configuration section
        /// </summary>
        /// <param name="configSection"></param>
        public SPOptions(KentorAuthServicesSection configSection)
        {
            if (configSection == null)
            {
                throw new ArgumentNullException(nameof(configSection));
            }
            systemIdentityModelIdentityConfiguration = new IdentityConfiguration(true);

            ReturnUrl             = configSection.ReturnUrl;
            MetadataCacheDuration = configSection.Metadata.CacheDuration;
            MetadataValidDuration = configSection.Metadata.ValidUntil;
            WantAssertionsSigned  = configSection.Metadata.WantAssertionsSigned;
            ValidateCertificates  = configSection.ValidateCertificates;
            DiscoveryServiceUrl   = configSection.DiscoveryServiceUrl;
            EntityId     = configSection.EntityId;
            ModulePath   = configSection.ModulePath;
            PublicOrigin = configSection.PublicOrigin;
            Organization = configSection.Organization;
            AuthenticateRequestSigningBehavior = configSection.AuthenticateRequestSigningBehavior;
            NameIdPolicy = new Saml2NameIdPolicy(
                configSection.NameIdPolicyElement.AllowCreate, configSection.NameIdPolicyElement.Format);
            RequestedAuthnContext = new Saml2RequestedAuthnContext(configSection.RequestedAuthnContext);

            configSection.ServiceCertificates.RegisterServiceCertificates(this);

            foreach (var acs in configSection.AttributeConsumingServices)
            {
                AttributeConsumingServices.Add(acs);
            }

            foreach (var contact in configSection.Contacts)
            {
                Contacts.Add(contact);
            }
        }
Example #25
0
        /// <summary>
        /// Handles the <see cref="E:System.Web.HttpApplication.AuthenticateRequest" /> event from the ASP.NET pipeline.
        /// </summary>
        /// <param name="sender">The source for the event. This will be an <see cref="T:System.Web.HttpApplication" /> object.</param>
        /// <param name="eventArgs">The data for the event.</param>
        protected override void OnAuthenticateRequest(object sender, EventArgs eventArgs)
        {
            var request = HttpContext.Current.Request;
            var authenticationConfiguration = new AuthenticationConfiguration
            {
                RequireSsl         = false,
                EnableSessionToken = true,
                SessionToken       = new SessionTokenConfiguration
                {
                    HeaderName = "Authorization",
                    Scheme     = "Session",
                }
            };

            if (request.Headers.AllKeys.Any(k => k == authenticationConfiguration.SessionToken.HeaderName))
            {
                var header = request.Headers.Get(authenticationConfiguration.SessionToken.HeaderName);
                var parts  = header.Split(' ');
                if (parts.Length == 2)
                {
                    // if configured scheme was sent, try to authenticate the session token
                    if (parts[0] == authenticationConfiguration.SessionToken.Scheme)
                    {
                        var token = new JwtSecurityToken(parts[1]);

                        var identityConfiguratin = new IdentityConfiguration();
                        if (identityConfiguratin.IssuerNameRegistry is ConfigurationBasedIssuerNameRegistry)
                        {
                            var issuers = (identityConfiguratin.IssuerNameRegistry as ConfigurationBasedIssuerNameRegistry).ConfiguredTrustedIssuers;
                            if (issuers.Any(i => i.Value == token.Issuer))
                            {
                                var issuer = issuers.FirstOrDefault(i => i.Value == token.Issuer);
                                var store  = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
                                store.Open(OpenFlags.ReadOnly);
                                var cert = store.Certificates.Find(X509FindType.FindByThumbprint, issuer.Key, false)[0];
                                store.Close();

                                var validationParameters = new TokenValidationParameters
                                {
                                    ValidIssuer      = issuer.Value,
                                    AllowedAudiences = identityConfiguratin.AudienceRestriction.AllowedAudienceUris.Select(uri => uri.OriginalString),
                                    SigningToken     = new X509SecurityToken(cert),
                                };

                                var handler         = new JwtSecurityTokenHandler();
                                var claimsPrinciple = handler.ValidateToken(token, validationParameters);
                                claimsPrinciple = identityConfiguratin.ClaimsAuthenticationManager.Authenticate(request.RawUrl, claimsPrinciple);
                                if (claimsPrinciple != null && claimsPrinciple.Identity.IsAuthenticated)
                                {
                                    HttpContext.Current.User = claimsPrinciple;
                                    Thread.CurrentPrincipal  = claimsPrinciple;
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            base.OnAuthenticateRequest(sender, eventArgs);
        }
        private InitializedFixture()
        {
            var issuerRegistry = new TrustedIssuerNameRegistry();

            if (X509Certificate == null)
            {
                X509Certificate = new X509Certificate2(@"CommonWellTokenTest.pfx", "commonwell");
            }
            if (IdentityConfigurationForTest == null)
            {
                IdentityConfigurationForTest = new IdentityConfiguration(false)
                {
                    AudienceRestriction       = { AudienceMode = AudienceUriMode.Never },
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    RevocationMode            = X509RevocationMode.NoCheck,
                    MaxClockSkew       = new TimeSpan(50000000),
                    IssuerNameRegistry = issuerRegistry,
                    ServiceCertificate = X509Certificate
                };

                IdentityConfigurationForTest.SecurityTokenHandlers.Clear();
                IdentityConfigurationForTest.SecurityTokenHandlers.Add(new CustomSaml2SecurityTokenHandler());
                IdentityConfigurationForTest.SecurityTokenHandlers.Add(new JwtSecurityTokenHandler());
                IdentityConfigurationForTest.SecurityTokenHandlers.Add(new X509SecurityTokenHandler());
            }
        }
 public IdentityCloudContext(IdentityConfiguration config)
 {
     if (config == null)
     {
         throw new ArgumentNullException("config");
     }
     Initialize(config);
 }
 public InternalContext(IdentityConfiguration config)
 {
     _client              = new CosmosClient(config.Uri, config.AuthKey, config.Options);
     _databaseId          = config.Database;
     _identityContainerId = config.IdentityCollection;
     InitDatabase();
     InitCollection();
 }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            ConventionsRemoveConfiguration.ConventionsRemove(modelBuilder.Model.GetEntityTypes());
            IdentityConfiguration.ConfigurationIdentityTables(modelBuilder);
            MappingConfiguration.RegisterMappings(modelBuilder);
        }
Example #30
0
        public static ApplicationDbContext Create()
        {
            var config = new IdentityConfiguration();

            config.StorageConnectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"].ToString();
            config.TablePrefix             = System.Configuration.ConfigurationManager.AppSettings["TablePrefix"].ToString();
            return(new ApplicationDbContext(config));
        }
Example #31
0
 public ApplicationDbContext(IdentityConfiguration config)
     : base(config)
 {
 }