public BarService(
            IConnection conn,
            IConfiguration config,
            SecurityOptions securityOptions)
            : base(conn, config, securityOptions)
        {
            var bangChannel = conn.CreateModel();
            var bangQueue   = $"bang-bar-reply-{Guid.NewGuid().ToString()}";

            bangChannel.QueueDeclare(bangQueue);
            _bangClient = new RpcClient(
                bangChannel,
                new PublishOptions(config["RabbitMQ:Services:Bang"]),
                new ConsumeOptions(bangQueue),
                new JsonFormatOptions());

            var fibChannel = conn.CreateModel();
            var fibQueue   = $"fib-bar-reply-{Guid.NewGuid().ToString()}";

            fibChannel.QueueDeclare(fibQueue);
            _fibClient = new RpcClient(
                fibChannel,
                new PublishOptions(config["RabbitMQ:Services:Fib"]),
                new ConsumeOptions(fibQueue),
                new JsonFormatOptions());
        }
 public DailyTaskAppService(
     ILogger <DailyTaskAppService> logger,
     IOptionsMonitor <Dictionary <string, int> > dicOptions,
     IAccountDomainService loginDomainService,
     IVideoDomainService videoDomainService,
     IDonateCoinDomainService donateCoinDomainService,
     IMangaDomainService mangaDomainService,
     ILiveDomainService liveDomainService,
     IVipPrivilegeDomainService vipPrivilegeDomainService,
     IChargeDomainService chargeDomainService,
     IOptionsMonitor <SecurityOptions> securityOptions,
     IOptionsMonitor <DailyTaskOptions> dailyTaskOptions,
     ICoinDomainService coinDomainService
     )
 {
     _logger                    = logger;
     _expDic                    = dicOptions.Get(Constants.OptionsNames.ExpDictionaryName);
     _loginDomainService        = loginDomainService;
     _videoDomainService        = videoDomainService;
     _donateCoinDomainService   = donateCoinDomainService;
     _mangaDomainService        = mangaDomainService;
     _liveDomainService         = liveDomainService;
     _vipPrivilegeDomainService = vipPrivilegeDomainService;
     _chargeDomainService       = chargeDomainService;
     _dailyTaskOptions          = dailyTaskOptions.CurrentValue;
     _coinDomainService         = coinDomainService;
     _securityOptions           = securityOptions.CurrentValue;
 }
 public BangService(
     IConnection conn,
     IConfiguration config,
     SecurityOptions securityOptions)
     : base(conn, config, securityOptions)
 {
 }
Пример #4
0
        public static IServiceCollection SetupAuthorization(
            this IServiceCollection services, IConfiguration configuration)
        {
            // configure jwt authentication
            SecurityOptions appSettings = configuration
                                          .GetSection(nameof(SecurityOptions))
                                          .Get <SecurityOptions>();

            byte[] key = Encoding.ASCII.GetBytes(appSettings.SecretKey);

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true
                };
            });

            return(services);
        }
Пример #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigureSwaggerGenOptions"/> class.
        /// </summary>
        /// <param name="provider">The <see cref="IApiVersionDescriptionProvider">provider</see> used to generate Swagger documents.</param>
        public ConfigureSwaggerGenOptions(
            IApiVersionDescriptionProvider apiVersionDescriptionProvider,
            IHttpClientFactory httpClientFactory,
            IOptions <OpenApiInfo> apiInfoAccessor,
            IOptions <SecurityOptions> swaggerUIClientSettings,
            IAssemblyMarkerTypes assemblyMarkerTypes,
            IWebHostEnvironment environment)
        {
            _apiVersionDescriptionProvider = apiVersionDescriptionProvider ?? throw new ArgumentNullException(nameof(apiVersionDescriptionProvider));
            _httpClientFactory             = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
            _assemblyMarkerTypes           = assemblyMarkerTypes ?? throw new ArgumentNullException(nameof(assemblyMarkerTypes));
            _apiInfo = apiInfoAccessor.Value ?? throw new ArgumentNullException(nameof(apiInfoAccessor));

            if (string.IsNullOrWhiteSpace(_apiInfo?.Title))
            {
                throw new InvalidOperationException("No API information (such as title etc.) has been passed." +
                                                    "Maybe it is missing from the configuration file or not registered in the dependency injection container.");
            }

            _swaggerUIClientSettings = swaggerUIClientSettings.Value ?? throw new ArgumentNullException(nameof(swaggerUIClientSettings));

            // We don't ensure that valid JWT information (such as Authority etc.) has been passed at this stage.
            // If it has not, we simply won't configure the Swagger UI to authenticate endpoint calls.

            bool isDevelopmentEnvironment = environment.IsDevelopment();

            if (_swaggerUIClientSettings.Jwt is null && !isDevelopmentEnvironment)
            {
                throw new InvalidOperationException("No JWT information (such as Authority etc.) has been passed. Maybe it is missing from the configuration file or not registered in the dependency injection container.");
            }
        }
Пример #6
0
 public BackgroundJobHelper(IWebHostEnvironment env, AppDBContext context, IOptions <SecurityOptions> securityOptions, IEmailService emailService)
 {
     _env             = env;
     _context         = context;
     _securityOptions = securityOptions.Value;
     _emailService    = emailService;
 }
    public void Start()
    {
        // create a new ManualResetEvent. This will be used to make the main application
        // thread wait until the full server reply has been received.
        m_ResetEvent = new ManualResetEvent(false);
        // initialize the security options
        SecurityOptions options = new SecurityOptions(
            SecureProtocol.Ssl3 | SecureProtocol.Tls1,                  // use SSL3 or TLS1
            null,                                                       // do not use client authentication
            ConnectionEnd.Client,                                       // this is the client side
            CredentialVerification.None,                                // do not check the certificate -- this should not be used in a real-life application :-)
            null,                                                       // not used with automatic certificate verification
            "www.microsoft.com",                                        // this is the common name of the Microsoft web server
            SecurityFlags.Default,                                      // use the default security flags
            SslAlgorithms.SECURE_CIPHERS,                               // only use secure ciphers
            null);                                                      // do not process certificate requests.

        try {
            // create the securesocket with the specified security options
            m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
            // resolve www.microsoft.com
            IPEndPoint endpoint = new IPEndPoint(Dns.Resolve("www.microsoft.com").AddressList[0], 443);
            // start connecting to www.microsoft.com
            m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
            // wait until the entire web page has been received
            m_ResetEvent.WaitOne();
            // close the SecureSocket
            m_Socket.Close();
        } catch {
            OnError("Could not connect to the website");
        }
    }
Пример #8
0
        /// <summary>
        /// Creates an HTTPS socket binding to the specified port
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public virtual AdkSocketBinding CreateHttpsListener(SecurityOptions options)
        {
            AdkSSLAcceptSocket socket  = new AdkSSLAcceptSocket(options);
            AdkSocketBinding   binding = new AdkSocketBinding(socket);

            return(binding);
        }
Пример #9
0
        // iterator to scan next channel page
        private void ScanNextPage()
        {
            for (; ;)
            {
                if (_scanChannels == null || _scanChannelsCurrent > _scanChannels.Length - 1) // array starts at 0
                {
                    FinishScanning(Status.Success);
                    return;
                }

                UInt32 channels = (UInt32)_scanChannels[_scanChannelsCurrent];
                UInt32 page     = (channels >> 27);
                channels &= 0x07FFFFFF; // remove page
                _scanChannelsCurrent++;

                if (channels != 0) // skip empty pages
                {
                    SecurityOptions so = new SecurityOptions();
                    so.SecurityLevel = SecurityLevelIdentifier.None;

                    // FIXME: how to select scanDuration?
                    byte scanDuration = 5;
                    _net.Mac.ScanRequest(ScanType.ActiveScan, channels, scanDuration, (byte)page, so, HandlerScanResult);
                    return;
                }
            }
        }
Пример #10
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)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());

            app.UseResponseCompression();

            var securityOptions = new SecurityOptions();

            Configuration.GetSection("Security").Bind(securityOptions);

            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority            = securityOptions.Authority,
                AllowedScopes        = securityOptions.AllowedScopes,
                RequireHttpsMetadata = securityOptions.RequireHttpsMetadata
            });

            app.UseMvc();
        }
Пример #11
0
 public ApiFileShareController(IWebHostEnvironment env, AppDBContext context, IOptions <SecurityOptions> securityOptions, IEmailService emailService)
 {
     _env             = env;
     _context         = context;
     _securityOptions = securityOptions.Value;
     _emailService    = emailService;
 }
Пример #12
0
        public void should_create_security_config()
        {
            var ipAllowedList = new List <string>()
            {
                "127.0.0.1", "192.168.1.1"
            };
            var ipBlockedList = new List <string>()
            {
                "127.0.0.1", "192.168.1.1"
            };
            var fileReRoute = new FileReRoute
            {
                SecurityOptions = new FileSecurityOptions()
                {
                    IPAllowedList = ipAllowedList,
                    IPBlockedList = ipBlockedList
                }
            };

            var expected = new SecurityOptions(ipAllowedList, ipBlockedList);

            this.Given(x => x.GivenThe(fileReRoute))
            .When(x => x.WhenICreate())
            .Then(x => x.ThenTheResultIs(expected))
            .BDDfy();
        }
Пример #13
0
        private void ConnectClient(SecureProtocol protocol)
        {
            lock (this)
            {
                if (connected)
                {
                    throw new Exception("Connection with IRC server already opened.");
                }
                Debug.WriteLineIf(Rfc2812Util.IrcTrace.TraceInfo, "[" + Thread.CurrentThread.Name + "] Connection::Connect()");

                SecurityOptions options = new SecurityOptions(protocol);
                options.Certificate       = null;
                options.Entity            = ConnectionEnd.Client;
                options.VerificationType  = CredentialVerification.None;
                options.Flags             = SecurityFlags.Default;
                options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
                client = new SecureTcpClient(options);
                client.Connect(connectionArgs.Hostname, connectionArgs.Port);

                connected               = true;
                writer                  = new StreamWriter(client.GetStream(), TextEncoding);
                writer.AutoFlush        = true;
                reader                  = new StreamReader(client.GetStream(), TextEncoding);
                socketListenThread      = new Thread(new ThreadStart(ReceiveIRCMessages));
                socketListenThread.Name = Name;
                socketListenThread.Start();
                sender.RegisterConnection(connectionArgs);
            }
        }
Пример #14
0
        public static IServiceCollection AddAuthorizationPolicies(this IServiceCollection services, Action <SecurityOptions> configureAction = null)
        {
            var options = new SecurityOptions();

            configureAction?.Invoke(options);

            services.AddAuthorization(x =>
            {
                x.AddPolicy(Policies.CreatePeople, p =>
                {
                    p.RequireClaimExtended(services, options, options.Claims.PermissionClaim, Permissions.CreatePeople);
                });
                x.AddPolicy(Policies.RetrievePeople, p =>
                {
                    p.RequireClaimExtended(services, options, options.Claims.PermissionClaim, Permissions.RetrievePeople);
                });
                x.AddPolicy(Policies.UpdatePeople, p =>
                {
                    p.RequireClaimExtended(services, options, options.Claims.PermissionClaim, Permissions.UpdatePeople);
                });
                x.AddPolicy(Policies.DeletePeople, p =>
                {
                    p.RequireClaimExtended(services, options, options.Claims.PermissionClaim, Permissions.DeletePeople);
                });
            });
            return(services);
        }
Пример #15
0
        /// <summary>
        /// Create a new scopde domain service instance
        /// </summary>
        /// <param name="authenticatedUser">Authenticated user object</param>
        /// <param name="uow">Unit of Work object</param>
        /// <param name="repository">User repository service</param>
        /// <param name="credentialRepository">Credential repository service</param>
        /// <param name="tokenRepository">User credential token repository service</param>
        /// <param name="scopeRepository">Scope repository</param>
        /// <param name="roleRepository">Role repository</param>
        /// <param name="securityOptions">Security options configuration</param>
        /// <param name="credentialOptions">Credential options configuration</param>
        /// <param name="localizer">Language string localizer</param>
        public UserDomainService
        (
            IAuthenticatedUser authenticatedUser,
            IUnitOfWork uow,
            IUserRepository repository,
            IUserCredentialRepository credentialRepository,
            IUserCredentialTokenRepository tokenRepository,
            IScopeRepository scopeRepository,
            IRoleRepository roleRepository,
            IOptions <SecurityOptions> securityOptions,
            IOptions <CredentialOptions> credentialOptions,
            IStringLocalizer <UserDomainService> localizer
        ) : base(repository, authenticatedUser)
        {
            _uow                  = uow;
            _repository           = repository;
            _credentialRepository = credentialRepository;
            _tokenRepository      = tokenRepository;
            _scopeRepository      = scopeRepository;
            _roleRepository       = roleRepository;

            _securityOptions   = securityOptions?.Value;
            _credentialOptions = credentialOptions?.Value;
            _localizer         = localizer;
        }
Пример #16
0
        public static void AddAuthentication(this IServiceCollection services, SecurityOptions options)
        {
            _signing    = _signing ?? BuildSigningCredentials(options);
            _encrypting = _encrypting ?? BuildEncryptingCredentials(options);

            services
            .AddAuthentication(x =>
            {
                x.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignInScheme    = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.TokenValidationParameters = BuildTokenValidationParameters(options);
#if DEBUG
                x.IncludeErrorDetails  = true;
                x.RequireHttpsMetadata = false;
#else
                x.IncludeErrorDetails  = false;
                x.RequireHttpsMetadata = true;
#endif
            })
            .AddCookie(cfg => cfg.SlidingExpiration = true);
        }
Пример #17
0
        public async Task <Response> Security(DownstreamContext context)
        {
            IPAddress       clientIp        = context.HttpContext.Connection.RemoteIpAddress;
            SecurityOptions securityOptions = context.DownstreamReRoute.SecurityOptions;

            if (securityOptions == null)
            {
                return(new OkResponse());
            }

            if (securityOptions.IPBlockedList != null)
            {
                if (securityOptions.IPBlockedList.Exists(f => f == clientIp.ToString()))
                {
                    var error = new UnauthenticatedError($" This request rejects access to {clientIp.ToString()} IP");
                    return(new ErrorResponse(error));
                }
            }

            if (securityOptions.IPAllowedList != null && securityOptions.IPAllowedList.Count > 0)
            {
                if (!securityOptions.IPAllowedList.Exists(f => f == clientIp.ToString()))
                {
                    var error = new UnauthenticatedError($"{clientIp.ToString()} does not allow access, the request is invalid");
                    return(new ErrorResponse(error));
                }
            }

            return(await Task.FromResult(new OkResponse()));
        }
Пример #18
0
        public void StartRequest(
            UInt16 panId,
            Byte logicalChannel,
            Byte channelPage,
            UInt16 startTime,
            byte beaconOrder,
            byte superframeOrder,
            bool panCoordinator,
            bool batteryLifeExtension,
            bool coordRealignment,
            SecurityOptions coordRealignSecutiryOptions,
            SecurityOptions beaconSecurityOptions,
            StartConfirmHandler handler)
        {
            TaskStartRequest task = new TaskStartRequest(
                panId,
                logicalChannel,
                channelPage,
                startTime,
                beaconOrder,
                superframeOrder,
                panCoordinator,
                batteryLifeExtension,
                coordRealignment,
                coordRealignSecutiryOptions,
                beaconSecurityOptions,
                handler);

            if (!_taskQueue.Add(task) && handler != null)
            {
                handler.Invoke(this, MacEnum.Congested);
            }
        }
Пример #19
0
        public ServerOptions Secured(string certExec, string certExecArgs, string serverCertThumbprint, X509Certificate2 clientCert)
        {
            if (certExec == null)
            {
                throw new ArgumentNullException(nameof(certExec));
            }
            if (certExecArgs == null)
            {
                throw new ArgumentNullException(nameof(certExecArgs));
            }
            if (serverCertThumbprint == null)
            {
                throw new ArgumentNullException(nameof(serverCertThumbprint));
            }
            if (clientCert == null)
            {
                throw new ArgumentNullException(nameof(clientCert));
            }

            if (Security != null)
            {
                throw new InvalidOperationException("The security has already been setup for this ServerOptions object");
            }

            Security = new SecurityOptions
            {
                ClientCertificate           = clientCert,
                CertificateExec             = certExec,
                CertificateArguments        = certExecArgs,
                ServerCertificateThumbprint = serverCertThumbprint
            };

            return(this);
        }
Пример #20
0
        public void DataRequest(
            MacAddressingMode srcAddrMode,
            MacAddress dstAddr,
            UInt16 dstPanId,
            ref Frame msdu,
            Byte msduHandle,
            TxOptions options,
            SecurityOptions securityOptions,
            DataConfirmHandler handler)
        {
            TaskDataRequest task = new TaskDataRequest(
                srcAddrMode,
                dstAddr,
                dstPanId,
                msdu,
                msduHandle,
                options,
                securityOptions,
                handler);

            if (!_taskQueue.Add(task))
            {
                Frame.Release(ref msdu);
                if (handler != null)
                {
                    handler.Invoke(this, msduHandle, MacEnum.Congested);
                }
            }

            msdu = null; // in any case, remove frame ownership from caller
        }
Пример #21
0
 public RolesAuthorizationRequirementExtended(SecurityOptions options, IEnumerable <string> allowedRoles)
 {
     Guard.AgainstNullArgument(nameof(options), options);
     Guard.AgainstNullArgument(nameof(allowedRoles), allowedRoles);
     _options     = options;
     AllowedRoles = allowedRoles ?? throw new ArgumentNullException(nameof(allowedRoles));
 }
Пример #22
0
 public AccountController(AppDBContext context, IOptions <SecurityOptions> securityOptions, IEmailService emailService, IOptions <JwtIssuerOptions> jwtOptions)
 {
     _context         = context;
     _securityOptions = securityOptions.Value;
     _emailService    = emailService;
     _jwtOptions      = jwtOptions.Value;
 }
Пример #23
0
        /// <summary>
        /// Prepare request
        /// </summary>
        /// <param name="options">Options to security connection</param>
        /// <param name="requestMethod">Request method to execute</param>
        /// <param name="handler">Handler name used in solr request</param>
        /// <param name="data">Data to execute</param>
        /// <returns>WebRequest read to execute</returns>
        private WebRequest Prepare(SecurityOptions options, string requestMethod, string handler, string data)
        {
            var baseUrl = $"{this.HostAddress}/{handler}";

            var encoding = new UTF8Encoding();
            var bytes    = encoding.GetBytes(data);

            var request = WebRequest.Create(baseUrl);

            if (options.AuthenticationType == AuthenticationType.Basic)
            {
                var encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(options.UserName + ":" + options.Password));
                request.Headers[HttpRequestHeader.Authorization] = "Basic " + encoded;
            }

            request.Method        = requestMethod;
            request.ContentType   = "application/json";
            request.ContentLength = bytes.Length;
            var stream = request.GetRequestStream();

            stream.Write(bytes, 0, bytes.Length);
            stream.Close();

            return(request);
        }
Пример #24
0
 public CompatibilityLayer(SocketController controller, SecurityOptions options)
 {
     m_Buffer     = new byte[0];
     m_MinVersion = GetMinProtocol(options.Protocol);
     m_MaxVersion = GetMaxProtocol(options.Protocol);
     if (m_MinVersion.GetVersionInt() == 30)               // SSL 3.0
     {
         if (options.Entity == ConnectionEnd.Client)
         {
             m_MinLayer = new RecordLayer(controller, new Ssl3ClientHandshakeLayer(null, options));
         }
         else
         {
             m_MinLayer = new RecordLayer(controller, new Ssl3ServerHandshakeLayer(null, options));
         }
     }
     else                 // TLS 1.0
     {
         if (options.Entity == ConnectionEnd.Client)
         {
             m_MinLayer = new RecordLayer(controller, new Tls1ClientHandshakeLayer(null, options));
         }
         else
         {
             m_MinLayer = new RecordLayer(controller, new Tls1ServerHandshakeLayer(null, options));
         }
     }
     m_MinLayer.HandshakeLayer.RecordLayer = m_MinLayer;
     m_Options = options;
 }
Пример #25
0
 public TaskStartRequest(
     UInt16 panId,
     Byte logicalChannel,
     Byte channelPage,
     UInt16 startTime,
     byte beaconOrder,
     byte superframeOrder,
     bool panCoordinator,
     bool batteryLifeExtension,
     bool coordRealignment,
     SecurityOptions coordRealignSecutiryOptions,
     SecurityOptions beaconSecurityOptions,
     StartConfirmHandler handler)
     : base(TaskType.StartRequest)
 {
     this.panId                       = panId;
     this.logicalChannel              = logicalChannel;
     this.channelPage                 = channelPage;
     this.startTime                   = startTime;
     this.beaconOrder                 = beaconOrder;
     this.superframeOrder             = superframeOrder;
     this.panCoordinator              = panCoordinator;
     this.batteryLifeExtension        = batteryLifeExtension;
     this.coordRealignment            = coordRealignment;
     this.coordRealignSecutiryOptions = coordRealignSecutiryOptions;
     this.beaconSecurityOptions       = beaconSecurityOptions;
     this.handler                     = handler;
 }
Пример #26
0
        public static void AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            var securityOptions = new SecurityOptions();

            configuration.GetSection("Security").Bind(securityOptions);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityOptions.JwtSigningKey)),
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ClockSkew        = TimeSpan.FromMinutes(5),
                    ValidAudience    = securityOptions.Audience,
                    ValidIssuer      = securityOptions.Issuer
                };
            });
        }
Пример #27
0
        public void Execute(IServiceCollection serviceCollection, IServiceProvider serviceProvider)
        {
            SecurityOptions securityOptions = serviceProvider.GetService <IOptions <SecurityOptions> >()?.Value;

            if (securityOptions.EnableAuthentication)
            {
                serviceCollection.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.AccessDeniedPath   = securityOptions.AccessDeniedPath;
                    options.LoginPath          = securityOptions.LoginPath;
                    options.LogoutPath         = securityOptions.LogoutPath;
                    options.ReturnUrlParameter = securityOptions.ReturnUrlParameter;
                    options.ExpireTimeSpan     = TimeSpan.FromDays(7);
                }
                           );
            }

            else
            {
                serviceCollection.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.AccessDeniedPath   = "/backend/account/accessdenied";
                    options.LoginPath          = "/backend/account/signin";
                    options.LogoutPath         = "/backend/account/signout";
                    options.ReturnUrlParameter = "next";
                    options.ExpireTimeSpan     = TimeSpan.FromDays(7);
                }
                           );
            }
        }
Пример #28
0
 public SocketController(SecureSocket parent, Socket socket, SecurityOptions options)
 {
     m_Parent          = parent;
     m_Socket          = socket;
     m_IsDisposed      = false;
     m_ActiveSend      = null;
     m_ActiveReceive   = null;
     m_DecryptedBuffer = new XBuffer();
     m_ToSendList      = new ArrayList(2);
     m_SentList        = new ArrayList(2);
     m_ReceiveBuffer   = new byte[m_ReceiveBufferLength];
     m_Compatibility   = new CompatibilityLayer(this, options);
     //			m_RecordLayer = new RecordLayer(this, options);
     try {
         m_Socket.BeginReceive(m_ReceiveBuffer, 0, m_ReceiveBufferLength, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
     } catch (Exception e) {
         CloseConnection(e);
     }
     if (options.Entity == ConnectionEnd.Client)
     {
         //				byte[] hello = m_RecordLayer.GetControlBytes(ControlType.ClientHello);
         byte[] hello = m_Compatibility.GetClientHello();
         BeginSend(hello, 0, hello.Length, null, DataType.ProtocolData);
     }
 }
Пример #29
0
        private static TokenValidationParameters BuildTokenValidationParameters(SecurityOptions options)
        {
            if (options.Tokens.Encrypt)
            {
                return(new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    ValidIssuer = options.Tokens.Issuer,
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidAudience = options.Tokens.Audience,
                    RequireSignedTokens = false,
                    TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Tokens.Key)),
                    ClockSkew = TimeSpan.FromSeconds(options.Tokens.ClockSkewSeconds),
                    RoleClaimType = options.Claims.RoleClaim,
                    NameClaimType = options.Claims.UserNameClaim
                });
            }

            return(new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                ValidIssuer = options.Tokens.Issuer,
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidAudience = options.Tokens.Audience,
                RequireSignedTokens = true,
                IssuerSigningKey = _signing.Key,
                ClockSkew = TimeSpan.FromSeconds(options.Tokens.ClockSkewSeconds),
                RoleClaimType = options.Claims.RoleClaim,
                NameClaimType = options.Claims.UserNameClaim
            });
        }
Пример #30
0
        public void Connect(string hostname, int port, bool ssl)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                var             protocol = ssl ? SecureProtocol.Tls1 | SecureProtocol.Ssl3 : SecureProtocol.None;
                SecurityOptions options  = new SecurityOptions(protocol);
                options.Certificate       = null;
                options.Entity            = ConnectionEnd.Client;
                options.CommonName        = hostname;
                options.VerificationType  = CredentialVerification.Auto;
                options.Flags             = SecurityFlags.Default;
                options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;

                //_Connection = new TcpClient(hostname, port);
                _Connection = new SecureTcpClient(hostname, port, options);
                _Stream     = _Connection.GetStream();

                _Reader = new StreamReader(_Stream, System.Text.Encoding.Default);
                string info = _Reader.ReadLine();
                OnConnected(info);

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                throw;
            }
        }
Пример #31
0
        public static IApplicationBuilder UseSecurity(this IApplicationBuilder app, SecurityOptions securityOptions)
        {
            app.UseOAuthBearerAuthentication(options =>
            {
                options.AutomaticAuthentication = true;
                options.Authority = securityOptions.Authority;
                    //TODO: avoid errors in the futre? github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/issues/94#issuecomment-118359248
                    options.TokenValidationParameters.ValidateAudience = false;
            });

            app.UseOpenIdConnectServer(options =>
            {
                options.AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;

                if (!securityOptions.IsMonoEnvironment)
                {
                    var rsaCryptoServiceProvider = new RSACryptoServiceProvider(2048);
                    var rsaParameters = rsaCryptoServiceProvider.ExportParameters(true);

                    options.UseKey(new RsaSecurityKey(rsaParameters));
                }
                else
                {
                    var temp = typeof(IApplicationBuilder).GetTypeInfo().Assembly;
                    options.UseCertificate(typeof(IApplicationBuilder).GetTypeInfo().Assembly, "ASP5.Template.Web.Certificate.pfx", "Owin.Security.OpenIdConnect.Server");
                }

                options.ApplicationCanDisplayErrors = true;
                options.AllowInsecureHttp = true;
                options.Issuer = new Uri(securityOptions.Authority);
                options.TokenEndpointPath = new PathString("/token");
                options.AuthorizationEndpointPath = PathString.Empty;
                options.AccessTokenLifetime = securityOptions.TokenLifeTime;
                options.ValidationEndpointPath = PathString.Empty;
                options.Provider = new DefaultAuthorizationProvider();
            });
            return app;
        }
Пример #32
0
		public SocketController(SecureSocket parent, Socket socket, SecurityOptions options) {
			m_Parent = parent;
			m_Socket = socket;
			m_IsDisposed = false;
			m_ActiveSend = null;
			m_ActiveReceive = null;
			m_DecryptedBuffer = new XBuffer();
			m_ToSendList = new ArrayList(2);
			m_SentList = new ArrayList(2);
			m_ReceiveBuffer = new byte[m_ReceiveBufferLength];
			m_Compatibility = new CompatibilityLayer(this, options);
			//			m_RecordLayer = new RecordLayer(this, options);
			try {
				m_Socket.BeginReceive(m_ReceiveBuffer, 0, m_ReceiveBufferLength, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
			} catch (Exception e) {
				CloseConnection(e);
			}
			if (options.Entity == ConnectionEnd.Client) {
				//				byte[] hello = m_RecordLayer.GetControlBytes(ControlType.ClientHello);
				byte[] hello = m_Compatibility.GetClientHello();
				BeginSend(hello, 0, hello.Length, null, DataType.ProtocolData);
			}
		}
Пример #33
0
        public SocketController(SecureSocket parent, Socket socket, SecurityOptions options)
        {
            this.m_Parent = parent;
            this.m_Socket = socket;
            this.m_IsDisposed = false;
            this.m_ActiveSend = null;
            this.m_ActiveReceive = null;
            this.m_DecryptedBuffer = new XBuffer();
            this.m_ToSendList = new ArrayList(2);
            this.m_SentList = new ArrayList(2);
            this.m_ReceiveBuffer = new byte[m_ReceiveBufferLength];
            this.m_End = options.Entity;

            this.OnConnectionClose += parent.ConnectionCloseHandler;

            this.m_Compatibility = new CompatibilityLayer(this, options);
        }
Пример #34
0
 public ServerHandshakeLayer(RecordLayer recordLayer, SecurityOptions options)
     : base(recordLayer, options)
 {
 }