Exemplo n.º 1
0
 public void AuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
 {
     //TBD: why are we enqueuing could be done on the peers fiber
     this.fiber.Enqueue(() =>
         this.OnAuthenticateClient(peer, authRequest, authSettings, sendParameters, state)
     );
 }
Exemplo n.º 2
0
        private void CreateForPlatform()
        {
            var forkMode = Settings.ForkMode.Value;

            switch (_platform.Value)
            {
            case Platform.AzureDevOps:
                CollaborationPlatform = new AzureDevOpsPlatform(_nuKeeperLogger);
                RepositoryDiscovery   = new AzureDevOpsRepositoryDiscovery(_nuKeeperLogger, Settings.Token);
                ForkFinder            = new AzureDevOpsForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);

                // We go for the specific platform version of ICommitWorder
                // here since Azure DevOps has different commit message limits compared to other platforms.
                CommitWorder = new AzureDevOpsCommitWorder();
                break;

            case Platform.GitHub:
                CollaborationPlatform = new OctokitClient(_nuKeeperLogger);
                RepositoryDiscovery   = new GitHubRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
                ForkFinder            = new GitHubForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
                CommitWorder          = new DefaultCommitWorder();
                break;

            case Platform.Bitbucket:
                CollaborationPlatform = new BitbucketPlatform(_nuKeeperLogger);
                RepositoryDiscovery   = new BitbucketRepositoryDiscovery(_nuKeeperLogger);
                ForkFinder            = new BitbucketForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
                CommitWorder          = new BitbucketCommitWorder();
                break;

            case Platform.BitbucketLocal:
                CollaborationPlatform = new BitBucketLocalPlatform(_nuKeeperLogger);
                RepositoryDiscovery   = new BitbucketLocalRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform, Settings);
                ForkFinder            = new BitbucketForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
                CommitWorder          = new DefaultCommitWorder();
                break;

            case Platform.GitLab:
                CollaborationPlatform = new GitlabPlatform(_nuKeeperLogger);
                RepositoryDiscovery   = new GitlabRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
                ForkFinder            = new GitlabForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
                CommitWorder          = new DefaultCommitWorder();
                break;

            case Platform.Gitea:
                CollaborationPlatform = new GiteaPlatform(_nuKeeperLogger);
                RepositoryDiscovery   = new GiteaRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
                ForkFinder            = new GiteaForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
                CommitWorder          = new DefaultCommitWorder();
                break;

            default:
                throw new NuKeeperException($"Unknown platform: {_platform}");
            }

            var auth = new AuthSettings(Settings.BaseApiUrl, Settings.Token, Settings.Username);

            CollaborationPlatform.Initialise(auth);

            if (ForkFinder == null ||
                RepositoryDiscovery == null ||
                CollaborationPlatform == null)
            {
                throw new NuKeeperException($"Platform {_platform} could not be initialised");
            }
        }
Exemplo n.º 3
0
 public AuthController(IOptions <AuthSettings> authSettings, IUsuarioService usuarioService)
 {
     _authSettings   = authSettings.Value;
     _usuarioService = usuarioService;
 }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // Укзывает, будет ли проверяться издатель при проверке токена
                    ValidateIssuer = false,
                    // Строка, представляющая издателя
                    ValidIssuer = AuthSettings.Issuer,

                    // Будет ли проверяться потребитель токена
                    ValidateAudience = false,
                    // Установка потребителя токена
                    ValidAudience = AuthSettings.Audience,
                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // установка ключа безопасности
                    IssuerSigningKey = AuthSettings.GetSymmetricSecurityKey(),
                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true,
                };
                // options.SaveToken = true;
            });

            // AutoMapper
            services.AddScoped(provider => new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile(provider.GetService <ApplicationDbContext>()));
            }).CreateMapper());

            services.AddCors();
            services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <ApplicationDbContext>(options => options
                                                 .UseLazyLoadingProxies()
                                                 .UseNpgsql(ConnectionString))
            .BuildServiceProvider();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "SlidEnglish", Version = "v1"
                });
                c.AddSecurityDefinition("Oauth2", new OAuth2Scheme
                {
                    Type     = "oauth2",
                    Flow     = "implicit",
                    TokenUrl = "/api/v1/tokens"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });

                c.DescribeAllEnumsAsStrings();

                c.OperationFilter <ResponseWithDescriptionOperationFilter>();
                c.OperationFilter <SecurityRequirementsOperationFilter>();

                c.SchemaFilter <EnumAsModelSchemaFilter>();
            });

            // AddIdentity и AddDefaultIdentity добавляют много чего лишнего. Ссылки для сранения.
            // https://github.com/aspnet/Identity/blob/c7276ce2f76312ddd7fccad6e399da96b9f6fae1/src/Core/IdentityServiceCollectionExtensions.cs
            // https://github.com/aspnet/Identity/blob/c7276ce2f76312ddd7fccad6e399da96b9f6fae1/src/Identity/IdentityServiceCollectionExtensions.cs
            // https://github.com/aspnet/Identity/blob/c7276ce2f76312ddd7fccad6e399da96b9f6fae1/src/UI/IdentityServiceCollectionUIExtensions.cs#L49
            services.AddIdentityCore <User>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddSingleton(x => AuthSettings);
            services.AddSingleton(x => GoogleCredential);

            services.AddSlidEnglishServices();
        }
Exemplo n.º 5
0
 public AuthController(IContextService contextService, IOptions <AuthSettings> authSettings)
 {
     _contextService = contextService;
     _authSettings   = authSettings.Value;
 }
Exemplo n.º 6
0
 public TokenService(IOptions <AuthSettings> authSettings)
 {
     _authSettings = authSettings.Value;
 }
 public AuthorizationController(IOptions <AuthSettings> settings, IAuthService authService)
 {
     _authService = authService;
     _settings    = settings.Value;
 }
Exemplo n.º 8
0
 public AuthenticationController(IAccountService accountService, IOptionsMonitor <AuthSettings> authOptions, IOptionsMonitor <JwtIssuerOptions> tokenOptions)
 {
     this.accountService   = accountService;
     signingConfigurations = authOptions.CurrentValue;
     tokenConfigurations   = tokenOptions.CurrentValue;
 }
Exemplo n.º 9
0
 public AppController(JiraContext dbContext, IOptions <AuthSettings> authOptions)
 {
     this.dbContext   = dbContext;
     this.authOptions = authOptions.Value;
 }
Exemplo n.º 10
0
 public AuthenticationService(JiraContext dbContext, IOptions <AuthSettings> authOptions)
 {
     this.dbContext = dbContext;
     authSettings   = authOptions.Value;
 }
Exemplo n.º 11
0
        public UserAccountService(IServiceProvider serviceProvider, IUnitOfWorkAsync unitOfWork) : base(unitOfWork)
        {
            _crypto = (ICrypto)serviceProvider.GetService(typeof(ICrypto));
            var settings = (IOptions <AppSettings>)serviceProvider.GetService(typeof(IOptions <AppSettings>));

            _settings = settings.Value;
            _logger   = (ILogger <UserAccountService>)serviceProvider.GetService(typeof(ILogger <UserAccountService>));

            Settings = settings.Value.Auth;

            AddEventHandler(new EmailUserAccountEventsHandler(serviceProvider));

            var accountvalidators = new UserAccountValidators();

            _usernameValidator = new Lazy <AggregateValidator <UserAccount> >(() =>
            {
                var val = new AggregateValidator <UserAccount>();
                if (!_settings.Auth.EmailIsUsername)
                {
                    val.Add(UserAccountValidation.UsernameDoesNotContainAtSign);
                    val.Add(UserAccountValidation.UsernameCanOnlyStartOrEndWithLetterOrDigit);
                    val.Add(UserAccountValidation.UsernameOnlyContainsValidCharacters);
                    val.Add(UserAccountValidation.UsernameOnlySingleInstanceOfSpecialCharacters);
                }
                val.Add(UserAccountValidation.UsernameMustNotAlreadyExist);
                val.Add(accountvalidators.UsernameValidator);
                return(val);
            });

            _emailValidator = new Lazy <AggregateValidator <UserAccount> >(() =>
            {
                var val = new AggregateValidator <UserAccount>
                {
                    UserAccountValidation.EmailIsRequiredIfRequireAccountVerificationEnabled,
                    UserAccountValidation.EmailIsValidFormat,
                    UserAccountValidation.EmailMustNotAlreadyExist,
                    accountvalidators.EmailValidator
                };
                return(val);
            });

            _phoneNumberValidator = new Lazy <AggregateValidator <UserAccount> >(() =>
            {
                var val = new AggregateValidator <UserAccount>
                {
                    UserAccountValidation.PhoneNumberIsRequiredIfRequireAccountVerificationEnabled,
                    UserAccountValidation.PhoneNumberMustNotAlreadyExist,
                    accountvalidators.PhoneNumberValidator
                };
                return(val);
            });

            _passwordValidator = new Lazy <AggregateValidator <UserAccount> >(() =>
            {
                var val = new AggregateValidator <UserAccount>
                {
                    UserAccountValidation.PasswordMustBeDifferentThanCurrent,
                    accountvalidators.PasswordValidator
                };
                return(val);
            });
        }
Exemplo n.º 12
0
 public void Initialise(AuthSettings settings)
 {
     _settings = settings ?? throw new ArgumentNullException(nameof(settings));
     _client   = new BitbucketLocalRestClient(_clientFactory, _logger, settings.Username, settings.Token, settings.ApiBase);
 }
Exemplo n.º 13
0
 public JwtService(AuthSettings authSettings)
 {
     _authSettings = authSettings;
 }
Exemplo n.º 14
0
 public AuthController(IOptions <AuthSettings> authSettings)
 {
     _authSettings = authSettings.Value;
 }
 public static IIssueTracker Factory(string url, string project, AuthSettings authentication)
 {
     return new JiraIssueTracker(url, project, authentication);
 }
Exemplo n.º 16
0
 public JwtHandler(AuthSettings authSettings)
 {
     this._authSettings = authSettings;
 }
 public JiraIssueTracker(string server, string project, AuthSettings authenticationInfo)
 {
     _server = server;
     _project = project;
     _authenticationInfo = authenticationInfo ?? new AuthSettings();
 }
Exemplo n.º 18
0
 public AuthController(EfcLinqJwtIntroContext context, IOptions <AuthSettings> authSettings)
 {
     _context      = context;
     _authSettings = authSettings.Value;
 }
Exemplo n.º 19
0
 public JwtTokenValidator(IOptions <AuthSettings> authSettings)
 {
     this.authSettings = authSettings.Value;
 }
Exemplo n.º 20
0
 public TokenService(IOptions <AuthSettings> authSettings)
 {
     _authSettings = authSettings?.Value ?? throw new ArgumentNullException(nameof(authSettings));
 }
Exemplo n.º 21
0
 public JwtTokenGeneratorService(IOptions <AuthSettings> authSettings)
 {
     _authSettings = authSettings.Value;
 }
Exemplo n.º 22
0
 private SettingsHandler(AuthSettings authSettings)
 => AuthSettings = authSettings;
Exemplo n.º 23
0
 public AuthController(IOptions <AuthSettings> authSettings, IAuthService authService)
 {
     _authSettings = authSettings.Value;
     _authService  = authService;
 }
Exemplo n.º 24
0
 public UserRepository(SportEventsDbContext context, IEmailSender emailSender, IOptions <AuthSettings> authSettings)
 {
     this.context      = context;
     this.emailSender  = emailSender;
     this.authSettings = authSettings.Value;
 }
Exemplo n.º 25
0
 public IdentityProvider(AuthSettings authSettings)
 {
     _authSettings = authSettings;
 }
Exemplo n.º 26
0
 public ClientTokenService(AuthSettings authSettings, IHttpContextAccessor httpContextAccessor)
 {
     this.authSettings        = authSettings;
     this.httpContextAccessor = httpContextAccessor;
 }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var cosmosDbConnectionContentPages = Configuration.GetSection(CosmosDbContentPagesConfigAppSettings).Get <CosmosDbConnection>();

            services.AddDocumentServices <CmsApiSharedContentModel>(cosmosDbConnectionContentPages, env.IsDevelopment());

            services.AddTransient <IEventMessageService <CmsApiSharedContentModel>, EventMessageService <CmsApiSharedContentModel> >();
            services.AddTransient <ICacheReloadService, CacheReloadService>();

            services.AddApplicationInsightsTelemetry();

            services.AddControllersWithViews();
            services.AddScoped <IDssReader, DssService>();
            services.AddScoped <IDssWriter, DssService>();
            services.AddAutoMapper(typeof(Startup).Assembly);
            services.AddTransient <IWebhooksService, WebhooksService>();
            services.AddTransient <IWebhookContentProcessor, WebhookContentProcessor>();

            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <ISkillsHealthCheckService, SkillsHealthCheckService>();
            services.AddScoped <IHttpWebRequestFactory, HttpWebRequestFactory>();
            services.Configure <DssSettings>(Configuration.GetSection(nameof(DssSettings)));
            services.Configure <CompositeSettings>(Configuration.GetSection(nameof(CompositeSettings)));
            services.Configure <ActionPlansSettings>(Configuration.GetSection(nameof(ActionPlansSettings)));
            services.Configure <AddressSearchServiceSettings>(
                Configuration.GetSection(nameof(AddressSearchServiceSettings)));
            services.Configure <ShcSettings>(Configuration.GetSection(nameof(ShcSettings)));
            services.Configure <AuthSettings>(Configuration.GetSection("AuthSettings"));
            services.AddScoped <IOpenIDConnectClient, AzureB2CAuthClient>();
            services.Configure <OpenIDConnectSettings>(Configuration.GetSection("OIDCSettings"));
            services.AddSingleton(Configuration.GetSection(nameof(CmsApiClientOptions)).Get <CmsApiClientOptions>() ?? new CmsApiClientOptions());
            services.AddHostedServiceTelemetryWrapper();
            services.AddSubscriptionBackgroundService(Configuration);
            services.AddHostedService <CacheReloadBackgroundService>();
            var authSettings = new AuthSettings();
            var appPath      = Configuration.GetSection("CompositeSettings:Path").Value;

            const string AppSettingsPolicies = "Policies";
            var          policyOptions       = Configuration.GetSection(AppSettingsPolicies).Get <PolicyOptions>() ?? new PolicyOptions();
            var          policyRegistry      = services.AddPolicyRegistry();

            services.AddApiServices(Configuration, policyRegistry);

            Configuration.GetSection("AuthSettings").Bind(authSettings);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidIssuer      = authSettings.Issuer,
                    ValidAudience    = authSettings.ClientId,
                    IssuerSigningKey =
                        new SymmetricSecurityKey(
                            Encoding.ASCII.GetBytes(authSettings.ClientSecret)),
                };
                cfg.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Redirect(appPath + "/session-timeout");
                        }
                        else
                        {
                            context.Response.Redirect(authSettings.SignInUrl);
                        }
                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        context.Response.Redirect(authSettings.SignInUrl);
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddSession();
            services.AddMvc().AddMvcOptions(options =>
            {
                options.Conventions.Add(new RouteTokenTransformerConvention(
                                            new HyphenControllerTransformer()));
            }).AddViewOptions(options =>
                              options.HtmlHelperOptions.ClientValidationEnabled = false);
        }
 public ApiAuthFilter(AuthSettings auth, IMediator mediator)
 {
     _mediator       = mediator;
     _authSettings   = auth;
     _authHeaderName = "Authorization";
 }
Exemplo n.º 29
0
 public AuthController(AuthSettings authSettings)
 {
     _authSettings = authSettings;
 }
Exemplo n.º 30
0
 public AuthService(IAuthRepository authRepository, IOptions <AuthSettings> authSettings)
 {
     _authRepository = authRepository;
     _authSettings   = authSettings.Value;
 }
Exemplo n.º 31
0
 /// <summary>
 /// Constructor for the dependency injection
 /// </summary>
 public AuthController(IUserRepository userRepository, IOptions <AuthSettings> settings)
 {
     _userRepository = userRepository;
     _authSettings   = settings.Value;
 }
Exemplo n.º 32
0
 public AuthService(IOptions <AuthSettings> options)
 {
     Settings = options.Value;
 }
        public static bool TryCreate(string url, string project, AuthSettings authentication, out IIssueTracker issueTracker)
        {
            // For now just check if it contains atlassian.net
            if (!string.IsNullOrWhiteSpace(url))
            {
                if (url.ToLower().Contains(".atlassian."))
                {
                    issueTracker = new JiraIssueTracker(url, project, authentication);
                    return true;
                }
            }

            issueTracker = null;
            return false;
        }
Exemplo n.º 34
0
 public AuthService(ILoggerAdapter <AuthService> logger, IOptions <AuthSettings> authSettings)
 {
     _logger       = logger;
     _authSettings = authSettings.Value;
 }
Exemplo n.º 35
0
 private Settings(AuthSettings auth, EnvironmentSettings environment)
 {
     Auth = auth;
     Environment = environment;
 }
Exemplo n.º 36
0
        protected virtual void OnAuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
        {
            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Authenticating client {0} - custom authentication type: {1}",
                         peer.ConnectionId,
                         authRequest.ClientAuthenticationType);
                }

                // when authentication data is provided check if
                // it is either a byte array or string and convert to byte array
                // if it's a string value
                byte[] authData = null;
                if (authRequest.ClientAuthenticationData != null)
                {
                    authData = authRequest.ClientAuthenticationData as byte[];
                    if (authData == null)
                    {
                        var stringData = authRequest.ClientAuthenticationData as string;
                        if (stringData == null)
                        {
                            peer.OnCustomAuthenticationError(
                                ErrorCode.CustomAuthenticationFailed,
                                "Authentication data type not supported",
                                authRequest,
                                sendParameters,
                                state);

                            this.IncrementFailedCustomAuth();
                            return;
                        }

                        authData = Encoding.UTF8.GetBytes(stringData);
                    }
                }

                if (string.IsNullOrEmpty(authRequest.ClientAuthenticationParams) && authData == null && this.isAnonymousAccessAllowed)
                {
                    // instant callback - treat as anonymous user:
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Authenticate client: grant access as anonymous user: conId={0}", peer.ConnectionId);
                    }

                    var customResult = new CustomAuthenticationResult { ResultCode = CustomAuthenticationResultCode.Ok };
                    peer.OnCustomAuthenticationResult(customResult, authRequest, sendParameters, state);
                    return;
                }

                // take auth type from auth request (default: custom)
                var authenticationType = (ClientAuthenticationType)authRequest.ClientAuthenticationType;

                ClientAuthenticationQueue authQueue;
                if (this.authenticationServices.TryGetValue(authenticationType, out authQueue) == false)
                {
                    if (log.IsWarnEnabled)
                    {
                        log.WarnFormat("Authentication type not supported: {0} for AppId={1}/{2}", authenticationType,
                            authRequest.ApplicationId, authRequest.ApplicationVersion);
                    }

                    peer.OnCustomAuthenticationError(
                        ErrorCode.CustomAuthenticationFailed,
                        "Authentication type not supported",
                        authRequest,
                        sendParameters,
                        state);
                    this.IncrementFailedCustomAuth();
                    return;
                }

                var queueState = new AuthQueueState(peer, authRequest, sendParameters, state);
                authQueue.EnqueueRequest(authRequest.ClientAuthenticationParams, authData, this.AuthQueueResponseCallback, queueState);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }