public void SetUp() { theSettings = new AuthenticationSettings(); theSystemTime = new SettableClock(); theRule = new LockedOutRule(theSettings, theSystemTime); }
public void exclude_by_default_if_the_input_type_is_marked_as_NotAuthenticated() { var chain = new BehaviorChain(); chain.AddToEnd(ActionCall.For<AuthenticatedEndpoints>(x => x.post_something(null))); var settings = new AuthenticationSettings(); settings.ShouldBeExcluded(chain).ShouldBeTrue(); }
public void apply_a_custome_exclusion_and_it_does_not_apply_to_login_page() { var settings = new AuthenticationSettings(); var chain = new BehaviorChain(); chain.AddToEnd(ActionCall.For<LoginController>(x => x.get_login(null))); settings.ShouldBeExcluded(chain).ShouldBeTrue(); settings.ExcludeChains.ChainMatches(c => c.Calls.Count() == 5); // just need a fake settings.ShouldBeExcluded(chain).ShouldBeTrue(); }
public void apply_a_custom_exclusion() { var chain = new BehaviorChain(); chain.AddToEnd(ActionCall.For<AuthenticatedEndpoints>(x => x.get_tag())); var settings = new AuthenticationSettings(); settings.ShouldBeExcluded(chain).ShouldBeFalse(); settings.ExcludeChains.ResourceTypeIs<HtmlTag>(); settings.ShouldBeExcluded(chain).ShouldBeTrue(); }
/// <summary> /// Retrieve a user's recording authentication settings. /// </summary> /// <param name="userId">The user Id.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The <see cref="AuthenticationSettings">settings</see>. /// </returns> public async Task <AuthenticationSettings> GetRecordingAuthenticationSettingsAsync(string userId, CancellationToken cancellationToken = default) { var response = await _client .GetAsync($"users/{userId}/settings") .WithArgument("option", "meeting_authentication") .WithCancellationToken(cancellationToken) .AsRawJsonObject() .ConfigureAwait(false); var settings = new AuthenticationSettings { RequireAuthentication = response.GetPropertyValue("recording_authentication", false), AuthenticationOptions = response.GetPropertyValue("authentication_options", Array.Empty <AuthenticationOptions>()) }; return(settings); }
public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, AuthenticationSettings authenticationSettings, IApiVersionDescriptionProvider provider) { return(app .UseSwagger(options => { options.PreSerializeFilters.Add((swaggerDoc, httpRequest) => swaggerDoc.Host = httpRequest.Host.Value); }) .UseSwaggerUI(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant() ); } options.OAuthClientId(authenticationSettings.Swagger.ClientId); options.OAuthAppName("WebAppTemplate Swagger UI"); options.OAuthAdditionalQueryStringParams(new Dictionary <string, string> { { "resource", authenticationSettings.AppIdUri } }); })); }
public SpotifyService(AuthenticationSettings settings) { _settings = settings; _authentication = new AuthorizationCodeAuth( clientId: _settings.ClientID, secretId: _settings.ClientSecret, redirectUri: _settings.RedirectURI, serverUri: _settings.RedirectURI, scope: Scope.UserReadPrivate | Scope.UserReadCurrentlyPlaying | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState); _api = new SpotifyWebAPI { AccessToken = _settings.Token.AccessToken, TokenType = "Bearer", UseAuth = true, }; }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var jwtSection = Configuration.GetSection("Authentication"); var jwtOptions = new AuthenticationSettings(); jwtSection.Bind(jwtOptions); services.AddAuthorization(options => { options.AddPolicy("admin", policy => policy.RequireRole("admin")); }); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key)), ValidIssuer = jwtOptions.Issuer, ValidateAudience = false, ValidateLifetime = true }; }); services.Configure <AuthenticationSettings>(jwtSection); services.AddMemoryCache(); services.AddMvc().AddJsonOptions(o => o.SerializerSettings.Formatting = Formatting.Indented); services.AddEntityFrameworkSqlServer() .AddEntityFrameworkInMemoryDatabase() .AddDbContext <DietPlannerContext>(); var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new ContainerModule(Configuration)); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); }
private List<PlexSearch> CachedLibraries(AuthenticationSettings authSettings, PlexSettings plexSettings, bool setCache) { Log.Trace("Obtaining library sections from Plex"); List<PlexSearch> results = new List<PlexSearch>(); if (!ValidateSettings(plexSettings, authSettings)) { Log.Warn("The settings are not configured"); return results; // don't error out here, just let it go! } try { if (setCache) { Log.Trace("Plex Lib API Call"); results = GetLibraries(authSettings, plexSettings); Log.Trace("Plex Lib Cache Set Call"); if (results != null) { Cache.Set(CacheKeys.PlexLibaries, results, CacheKeys.TimeFrameMinutes.SchedulerCaching); } } else { Log.Trace("Plex Lib GetSet Call"); results = Cache.GetOrSet(CacheKeys.PlexLibaries, () => { Log.Trace("Plex Lib API Call (inside getset)"); return GetLibraries(authSettings, plexSettings); }, CacheKeys.TimeFrameMinutes.SchedulerCaching); } } catch (Exception ex) { Log.Error(ex, "Failed to obtain Plex libraries"); } return results; }
public UpdateUserResponse UpdateUser(UpdateUserRequest request) { var user = FindUserByName(request.UserDetail.UserName); // update user account info var assembler = new UserAssembler(); assembler.UpdateUser(user, request.UserDetail, PersistenceContext); // reset password if requested if (request.UserDetail.ResetPassword) { var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); } PersistenceContext.SynchState(); return(new UpdateUserResponse(assembler.GetUserSummary(user))); }
private void ConfigureAuth(IServiceCollection services) { var auth = new AuthenticationSettings(); Configuration.GetSection("AuthenticationSettings").Bind(auth); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = auth.Authority, ValidAudience = auth.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(auth.SecretKey)) }; }); }
//[TestMethod] public async Task ExecuteServiceOnPortalAPI_Authenticated_OwnerFound_ReturnsPersonalInfo() { // Warning: This test is tied to existing information being retrieved from the External Resolver Api var authSettings = new AuthenticationSettings(InfrastructureConfiguration.AuthProviderUri, InfrastructureConfiguration.AuthProviderClient, InfrastructureConfiguration.AuthProviderSecret); IAuthenticationProvider authProvider = new AuthenticationProvider(authSettings); var service = new PersonalInfoExternalService(InfrastructureConfiguration.PortalExternalResolveUri, authProvider, new Mock <ILogger>().Object); var personalInfo = await service.FindPersonalInfoAsync("RP135685"); Assert.IsNotNull(personalInfo); Assert.AreEqual("J", personalInfo.Initials); Assert.AreEqual("Vries", personalInfo.LastNameAtBirth); Assert.AreEqual("V", personalInfo.LastNameAtBirthPrefix); Assert.AreEqual(1969, personalInfo.BirthDate.Year); Assert.AreEqual(8, personalInfo.BirthDate.Month); Assert.AreEqual(5, personalInfo.BirthDate.Day); }
private List<PlexSearch> GetLibraries(AuthenticationSettings authSettings, PlexSettings plexSettings) { var sections = PlexApi.GetLibrarySections(authSettings.PlexAuthToken, plexSettings.FullUri); List<PlexSearch> libs = new List<PlexSearch>(); if (sections != null) { foreach (var dir in sections.Directories) { Log.Trace("Obtaining results from Plex for the following library section: {0}", dir.Title); var lib = PlexApi.GetLibrary(authSettings.PlexAuthToken, plexSettings.FullUri, dir.Key); if (lib != null) { libs.Add(lib); } } } Log.Trace("Returning Plex Libs"); return libs; }
public AuthenticationHandler( ILoggerFactory loggerFactory, ConventionSettings conventionSettings, AuthenticationSettings authenticationSettings, IEntityRepository <RegSysAlternativePinRecord> regSysAlternativePinRepository, IEntityRepository <RegSysIdentityRecord> regSysIdentityRepository, ITokenFactory tokenFactory ) { _logger = loggerFactory.CreateLogger(GetType()); _conventionSettings = conventionSettings; _authenticationSettings = authenticationSettings; _regSysIdentityRepository = regSysIdentityRepository; _tokenFactory = tokenFactory; _authenticationProviders = new IAuthenticationProvider[] { new RegSysAlternativePinAuthenticationProvider(regSysAlternativePinRepository), new RegSysCredentialsAuthenticationProvider() }; }
public void LoginWithUsernameSuccessfully() { var expectedSettings = new AuthenticationSettings { UserAuthentication = true, PlexAuthToken = "abc" }; var plexFriends = new PlexFriends { User = new[] { new UserFriends { Title = "abc", }, } }; AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); PlexMock.Setup(x => x.GetUsers(It.IsAny <string>())).Returns(plexFriends); PlexMock.Setup(x => x.GetAccount(It.IsAny <string>())).Returns(new PlexAccount()); Bootstrapper.WithSession(new Dictionary <string, object>()); var browser = new Browser(Bootstrapper); var result = browser.Post("/userlogin", with => { with.HttpRequest(); with.Header("Accept", "application/json"); with.FormValue("Username", "abc"); }); Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc")); var body = JsonConvert.DeserializeObject <JsonResponseModel>(result.Body.AsString()); Assert.That(body.Result, Is.EqualTo(true)); AuthMock.Verify(x => x.GetSettings(), Times.Once); PlexMock.Verify(x => x.SignIn(It.IsAny <string>(), It.IsAny <string>()), Times.Never); PlexMock.Verify(x => x.GetUsers(It.IsAny <string>()), Times.Once); }
public void LoginWithUsernameUnSuccessfully() { var expectedSettings = new AuthenticationSettings { UserAuthentication = true }; var plexFriends = new PlexFriends { User = new[] { new UserFriends { Username = "******", }, } }; AuthMock.Setup(x => x.GetSettingsAsync()).ReturnsAsync(expectedSettings); PlexMock.Setup(x => x.GetUsers(It.IsAny <string>())).Returns(plexFriends); PlexMock.Setup(x => x.GetAccount(It.IsAny <string>())).Returns(new PlexAccount()); Bootstrapper.WithSession(new Dictionary <string, object>()); var browser = new Browser(Bootstrapper); var result = browser.Post("/userlogin", with => { with.HttpRequest(); with.Header("Accept", "application/json"); with.FormValue("Username", "abc"); }); Assert.That(HttpStatusCode.SeeOther, Is.EqualTo(result.StatusCode)); Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.Null); Assert.That(result.Headers.Contains(new KeyValuePair <string, string>("Location", "http://www.userloginindex.com/"))); // Redirect header AuthMock.Verify(x => x.GetSettingsAsync(), Times.Once); PlexMock.Verify(x => x.SignIn(It.IsAny <string>(), It.IsAny <string>()), Times.Never); PlexMock.Verify(x => x.GetUsers(It.IsAny <string>()), Times.Once); }
public async Task ValidateAsync_Success() { var authenticationSettings = new AuthenticationSettings { Microsoft = new MicrosoftAuthenticationSettings { ClientId = ClientId, }, }; var options = Options.Create(authenticationSettings); var configuration = new OpenIdConnectConfiguration(); configuration.JsonWebKeySet = new JsonWebKeySet(); configuration.JsonWebKeySet.Keys.Add(jsonWebKey); using (var http = new HttpClientTestingFactory()) { var tokenHandler = new JwtSecurityTokenHandler(); var token = new JwtSecurityToken( audience: ClientId, claims: new[] { new Claim("sub", ExternalUserId), new Claim("email", ExternalUserEmail) }, notBefore: DateTime.UtcNow, expires: DateTime.UtcNow + TimeSpan.FromHours(1), signingCredentials: new SigningCredentials(jsonWebKey, jsonWebKey.Alg)); var handler = new MicrosoftAssertionGrantHandler(options, http.HttpClient); var resultTask = handler.ValidateAsync(tokenHandler.WriteToken(token)); http.Expect(ConfigurationEndpoint).Respond(OpenIdConnectConfiguration.Write(configuration)); var result = await resultTask; Assert.NotNull(result); Assert.True(result.IsSuccessful); Assert.Equal(ExternalUserId, result.ExternalUserId); Assert.Equal(ExternalUserEmail, result.ExternalUserEmail); http.EnsureNoOutstandingRequests(); } }
public AdminController( IOptions <AuthenticationSettings> authSettings, IBlogAudit blogAudit, ICategoryService categoryService, IFriendLinkService friendLinkService, IPageService pageService, ITagService tagService, ICommentService commentService, IPingbackService pingbackService, IBlogConfig blogConfig) { _authenticationSettings = authSettings.Value; _categoryService = categoryService; _friendLinkService = friendLinkService; _pageService = pageService; _tagService = tagService; _commentService = commentService; _pingbackService = pingbackService; _blogConfig = blogConfig; _blogAudit = blogAudit; }
public static void AddSignalRJwtAuthentication(this IServiceCollection services, IConfiguration configuration) { var authenticationSettings = new AuthenticationSettings(); configuration.GetSection(nameof(AuthenticationSettings)).Bind(authenticationSettings); var secretInBytes = System.Text.Encoding.ASCII.GetBytes(authenticationSettings.Secret); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnMessageReceived = (context) => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/agenthub")) { context.Request.Headers.Add("Authorization", $"Bearer {accessToken}"); } return(Task.CompletedTask); } }; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(secretInBytes), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; options.RequireHttpsMetadata = false; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.RegisterPersistenceInstances(); services.RegisterApplicationInstances(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); // configure jwt authentication AuthenticationSettings authenticationSettings = services.GetAuthenticationSettings(Configuration); var key = Encoding.ASCII.GetBytes(authenticationSettings.Key); 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(key), ValidateIssuer = false, ValidateAudience = false }; }); }
public ResetUserPasswordResponse ResetUserPassword(ResetUserPasswordRequest request) { Platform.CheckForNullReference(request, "request"); Platform.CheckMemberIsSet(request.UserName, "UserName"); var user = FindUserByName(request.UserName); EnsureCurrentUserAuthorizedToManage(user.AccountType); if (user.AccountType != UserAccountType.U) { throw new RequestValidationException(SR.MessageAccountTypeDoesNotSupportPasswordReset); } var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); var assembler = new UserAssembler(); return(new ResetUserPasswordResponse(assembler.GetUserSummary(user))); }
public MetaWeblogService( IOptions <AuthenticationSettings> authOptions, IBlogConfig blogConfig, IDateTimeResolver dateTimeResolver, ILogger <MetaWeblogService> logger, ITagService tagService, ICategoryService categoryService, IPostService postService, IPageService pageService, IBlogImageStorage blogImageStorage, IFileNameGenerator fileNameGenerator) { _authenticationSettings = authOptions.Value; _blogConfig = blogConfig; _dateTimeResolver = dateTimeResolver; _logger = logger; _tagService = tagService; _categoryService = categoryService; _postService = postService; _pageService = pageService; _blogImageStorage = blogImageStorage; _fileNameGenerator = fileNameGenerator; }
private static Password GetNewAccountPassword(UserAccountType accountType, string password) { var settings = new AuthenticationSettings(); switch (accountType) { case UserAccountType.U: // for user accounts, always use the temp password, set to expire immediately return(Password.CreateTemporaryPassword(settings.DefaultTemporaryPassword)); case UserAccountType.G: // for group accounts, generate a random password (since it will never be used) return(Password.CreatePassword(Guid.NewGuid().ToString("N"), null)); case UserAccountType.S: // for system accounts, use password provided in request, and set to never expire PasswordPolicy.CheckPasswordCandidate(UserAccountType.S, password, settings); return(Password.CreatePassword(password, null)); default: throw new ArgumentOutOfRangeException("accountType"); } }
// 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentity(); // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715 app.UseFacebookAuthentication(AuthenticationSettings.FacebookOptions( Configuration["Facebook:AppId"], Configuration["Facebook:AppSecret"])); app.UseLinkedInAuthentication(AuthenticationSettings.LinkedInOptions( Configuration["LinkedIn:ClientId"], Configuration["LinkedIn:ClientSecret"])); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void LoginWithoutAuthentication() { var expectedSettings = new AuthenticationSettings { UserAuthentication = false, PlexAuthToken = "abc" }; AuthMock.Setup(x => x.GetSettings()).Returns(expectedSettings); var bootstrapper = new ConfigurableBootstrapper(with => { with.Module <UserLoginModule>(); with.Dependency(AuthMock.Object); with.Dependency(PlexMock.Object); with.Dependency(PlexRequestMock.Object); with.RootPathProvider <TestRootPathProvider>(); }); bootstrapper.WithSession(new Dictionary <string, object>()); var browser = new Browser(bootstrapper); var result = browser.Post("/userlogin", with => { with.HttpRequest(); with.Header("Accept", "application/json"); with.FormValue("Username", "abc"); }); Assert.That(HttpStatusCode.OK, Is.EqualTo(result.StatusCode)); Assert.That(result.Context.Request.Session[SessionKeys.UsernameKey], Is.EqualTo("abc")); var body = JsonConvert.DeserializeObject <JsonResponseModel>(result.Body.AsString()); Assert.That(body.Result, Is.EqualTo(true)); AuthMock.Verify(x => x.GetSettings(), Times.Once); PlexMock.Verify(x => x.SignIn(It.IsAny <string>(), It.IsAny <string>()), Times.Never); PlexMock.Verify(x => x.GetUsers(It.IsAny <string>()), Times.Never); }
public Authentication_UnitTests() { _authSettings = new AuthenticationSettings() { EnvClientID = "MOCK_CLIENTID", EnvUserName = "******", EnvUserPassword = "******", EnvClientSecret = "MOCK_CLIENTSECRET", Note = "MockNote", OAuth2Endpoint = "http://mock/", Scopes = new List <string>() { "mock_scope" } }; Environment.SetEnvironmentVariable("MOCK_CLIENTID", "mockClientId"); Environment.SetEnvironmentVariable("MOCK_USERNAME", "mockUsername"); Environment.SetEnvironmentVariable("MOCK_USERPASS", "mockPassword"); Environment.SetEnvironmentVariable("MOCK_CLIENTSECRET", "mockClientSecret"); _basicAuth = new BasicAuthentication(_authSettings); _oauth2Auth = new OAuth2Authentication(_authSettings); }
public void ConfigureServices(IServiceCollection services) { services.AddRateLimit(Configuration.GetSection("IpRateLimiting")); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(20); options.Cookie.HttpOnly = true; }); services.Configure <AppSettings>(Configuration.GetSection(nameof(AppSettings))); var authentication = new AuthenticationSettings(); Configuration.Bind(nameof(Authentication), authentication); services.AddLinkForwarderAuthenticaton(authentication); services.AddAntiforgery(options => { const string cookieBaseName = "CSRF-TOKEN-LFWDR"; options.Cookie.Name = $"X-{cookieBaseName}"; options.FormFieldName = $"{cookieBaseName}-FORM"; }); var conn = Configuration.GetConnectionString(Constants.DbName); services.AddTransient <IDbConnection>(c => new SqlConnection(conn)); services.AddSingleton <ITokenGenerator, ShortGuidTokenGenerator>(); services.AddTransient <ILinkForwarderService, LinkForwarderService>(); services.AddTransient <ILinkVerifier, LinkVerifier>(); services.AddApplicationInsightsTelemetry(); services.AddControllersWithViews(); services.AddRazorPages(); }
public static void InstallAuthentication(this IServiceCollection services, IConfiguration configuration) { var authenticationSettings = new AuthenticationSettings(); configuration.GetSection("Authentication").Bind(authenticationSettings); services.AddSingleton(authenticationSettings); services.AddAuthentication(option => { option.DefaultAuthenticateScheme = "Bearer"; option.DefaultScheme = "Bearer"; option.DefaultChallengeScheme = "Bearer"; }).AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtKey)), }; }); }
public ChannelMethodHandler(IServiceLocator services, Type channel, MethodInfo method, AuthenticationSettings settings, string baseURL, string channelHandlerId) { _services = services ?? throw new ArgumentNullException(nameof(services)); _method = method ?? throw new ArgumentNullException(nameof(method)); _channel = channel ?? throw new ArgumentNullException(nameof(channel)); _settings = settings; _baseURL = baseURL; _isManaged = false; _channelMethodDescriptor = _services.Get <IChannelMethodDescriptor>(); _requestActivator = _services.Get <IChannelMethodRequestActivator>(); _msgService = _services.Get <IChannelMessageService>(); _contextProvider = _services.Get <IChannelMethodContextProvider>(); _configuration = _services.Get <IChannelConfiguration>(); _authenticationService = _services.Get <IChannelAuthenticationService>(); _heuristics = _services.Get <IChannelHeuristics>(); _session = _services.Get <ISessionService>(); HandlerId = $"{Guid.NewGuid()}"; ChannelHandlerId = channelHandlerId; _isDisposed = false; _safeHandle = new SafeFileHandle(IntPtr.Zero, true); }
public AddUserResponse AddUser(AddUserRequest request) { Platform.CheckForNullReference(request, "request"); Platform.CheckMemberIsSet(request.UserDetail, "UserDetail"); var userDetail = request.UserDetail; var settings = new AuthenticationSettings(); // create new user var userInfo = new UserInfo(userDetail.UserName, userDetail.DisplayName, userDetail.EmailAddress, userDetail.ValidFrom, userDetail.ValidUntil); var user = User.CreateNewUser(userInfo, settings.DefaultTemporaryPassword); // copy other info such as authority groups from request var assembler = new UserAssembler(); assembler.UpdateUser(user, request.UserDetail, PersistenceContext); // save PersistenceContext.Lock(user, DirtyState.New); PersistenceContext.SynchState(); return new AddUserResponse(user.GetRef(), assembler.GetUserSummary(user)); }
public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddMemoryCache(); services.AddRateLimit(_configuration.GetSection("IpRateLimiting")); services.Configure <AppSettings>(_appSettingsSection); var authentication = new AuthenticationSettings(); _configuration.Bind(nameof(Authentication), authentication); services.Configure <AuthenticationSettings>(_configuration.GetSection(nameof(Authentication))); var imageStorage = new ImageStorageSettings(); _configuration.Bind(nameof(ImageStorage), imageStorage); services.Configure <ImageStorageSettings>(_configuration.GetSection(nameof(ImageStorage))); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(20); options.Cookie.HttpOnly = true; }); services.AddApplicationInsightsTelemetry(); services.AddMoongladeAuthenticaton(authentication); services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); services.AddAntiforgery(options => { const string cookieBaseName = "CSRF-TOKEN-MOONGLADE"; options.Cookie.Name = $"X-{cookieBaseName}"; options.FormFieldName = $"{cookieBaseName}-FORM"; }); services.AddMoongladeImageStorage(imageStorage, _environment.ContentRootPath); services.AddScoped(typeof(IRepository <>), typeof(DbContextRepository <>)); services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddSingleton <IBlogConfig, BlogConfig>(); services.AddScoped <IMoongladeAudit, MoongladeAudit>(); services.AddScoped <DeleteSubscriptionCache>(); services.AddScoped <ISiteIconGenerator, FileSystemSiteIconGenerator>(); services.AddScoped <IDateTimeResolver>(c => new DateTimeResolver(c.GetService <IBlogConfig>().GeneralSettings.TimeZoneUtcOffset)); services.AddScoped <IExportManager, ExportManager>(); services.AddScoped <IPingbackSender, PingbackSender>(); services.AddScoped <IPingbackReceiver, PingbackReceiver>(); services.AddScoped <IFileSystemOpmlWriter, FileSystemOpmlWriter>(); services.AddScoped <IFileNameGenerator>(gen => new GuidFileNameGenerator(Guid.NewGuid())); services.AddSessionBasedCaptcha(); var asm = Assembly.GetAssembly(typeof(MoongladeService)); if (null != asm) { var types = asm.GetTypes().Where(t => t.IsClass && t.IsPublic && t.Name.EndsWith("Service")); foreach (var t in types) { services.AddScoped(t, t); } } services.AddHttpClient <IMoongladeNotificationClient, NotificationClient>() .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(3, retryCount => TimeSpan.FromSeconds(Math.Pow(2, retryCount)), (result, span, retryCount, context) => { _logger?.LogWarning($"Request failed with {result.Result.StatusCode}. Waiting {span} before next retry. Retry attempt {retryCount}/3."); })); services.AddDbContext <MoongladeDbContext>(options => options.UseLazyLoadingProxies() .UseSqlServer(_configuration.GetConnectionString(Constants.DbConnectionName), sqlOptions => { sqlOptions.EnableRetryOnFailure( 3, TimeSpan.FromSeconds(30), null); })); }
public JwtTokenService(AuthenticationSettings authSettings) { _authSettings = authSettings; }
public HomeController(ILog log, AuthenticationSettings authenticationSettings) { _log = log; _authenticationSettings = authenticationSettings; }
public LoginController(ILoginCookies cookies, ILoginFailureHandler failureHandler, AuthenticationSettings settings) { _cookies = cookies; _failureHandler = failureHandler; _settings = settings; }
private static Password GetNewAccountPassword(UserAccountType accountType, string password) { var settings = new AuthenticationSettings(); switch (accountType) { case UserAccountType.U: // for user accounts, always use the temp password, set to expire immediately return Password.CreateTemporaryPassword(settings.DefaultTemporaryPassword); case UserAccountType.G: // for group accounts, generate a random password (since it will never be used) return Password.CreatePassword(Guid.NewGuid().ToString("N"), null); case UserAccountType.S: // for system accounts, use password provided in request, and set to never expire PasswordPolicy.CheckPasswordCandidate(password, settings); return Password.CreatePassword(password, null); default: throw new ArgumentOutOfRangeException("accountType"); } }
public LoginController(ILoginCookies cookies, AuthenticationSettings settings) { _cookies = cookies; _settings = settings; }
public UpdateUserResponse UpdateUser(UpdateUserRequest request) { var user = FindUserByName(request.UserDetail.UserName); EnsureCurrentUserAuthorizedToManage(user.AccountType); // update user account info var assembler = new UserAssembler(); assembler.UpdateUser(user, request.UserDetail, PersistenceContext); // for user accounts, reset password if requested if (request.UserDetail.ResetPassword) { if(user.AccountType != UserAccountType.U) throw new RequestValidationException(SR.MessageAccountTypeDoesNotSupportPasswordReset); var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); } // for system accounts, update the password if specified if(!string.IsNullOrEmpty(request.Password) && user.AccountType == UserAccountType.S) { PasswordPolicy.CheckPasswordCandidate(request.Password, new AuthenticationSettings()); user.ChangePassword(request.Password, null); } PersistenceContext.SynchState(); return new UpdateUserResponse(assembler.GetUserSummary(user)); }
public ResetUserPasswordResponse ResetUserPassword(ResetUserPasswordRequest request) { Platform.CheckForNullReference(request, "request"); Platform.CheckMemberIsSet(request.UserName, "UserName"); var user = FindUserByName(request.UserName); var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); var assembler = new UserAssembler(); return new ResetUserPasswordResponse(assembler.GetUserSummary(user)); }
public void exclude_by_default_actions_marked_as_pass_through() { var chain = new BehaviorChain(); chain.AddToEnd(ActionCall.For<AuthenticatedEndpoints>(x => x.get_pass_through_authentication())); var settings = new AuthenticationSettings(); settings.ShouldBeExcluded(chain).ShouldBeTrue(); }
public TicketAuthenticationSession(ITicketSource source, ISystemTime systemTime, AuthenticationSettings settings) { _source = source; _systemTime = systemTime; _settings = settings; }
public void excludes_is_always_false_with_no_exclusions() { var settings = new AuthenticationSettings(); settings.ShouldBeExcluded(new BehaviorChain()).ShouldBeFalse(); }
public async Task <bool> AuthenticationsSettings([FromBody] AuthenticationSettings settings) { return(await Save(settings)); }
public ResetUserPasswordResponse ResetUserPassword(ResetUserPasswordRequest request) { Platform.CheckForNullReference(request, "request"); Platform.CheckMemberIsSet(request.UserName, "UserName"); var user = FindUserByName(request.UserName); EnsureCurrentUserAuthorizedToManage(user.AccountType); if (user.AccountType != UserAccountType.U) throw new RequestValidationException(SR.MessageAccountTypeDoesNotSupportPasswordReset); var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); var assembler = new UserAssembler(); return new ResetUserPasswordResponse(assembler.GetUserSummary(user)); }
public static IServiceCollection ProtectWebApiWithJwtBearer(this IServiceCollection services, IConfiguration configuration) { // TODO WTS: Follow these steps to register your Web API and expose scopes and roles, // afterwards populate the appsettings.json with ClientId, Tenant, Audience and Scope // https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app // https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-expose-web-apis // To restrict access using roles: https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps // To assign users to your web api: https://docs.microsoft.com/azure/active-directory/develop/howto-restrict-your-app-to-a-set-of-users var settings = new AuthenticationSettings(); configuration.GetSection("AuthenticationSettings").Bind(settings); var tenantID = settings.TenantId; var audience = settings.Audience; var authority = $"https://login.windows.net/{tenantID}"; var configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>( $"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); var openIdConfig = configurationManager.GetConfigurationAsync(CancellationToken.None).GetAwaiter().GetResult(); // For multitenant scenarios and issuer validation please see // https://docs.microsoft.com/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant#update-your-code-to-handle-multiple-issuer-values // You can get a list of issuers for the various Azure AD deployments (global & sovereign) from the following endpoint // https://login.microsoftonline.com/common/discovery/instance?authorization_endpoint=https://login.microsoftonline.com/common/oauth2/v2.0/authorize&api-version=1.1; var validissuers = new List <string>() { "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0", $"https://login.microsoftonline.com/{tenantID}/", $"https://login.microsoftonline.com/{tenantID}/v2.0", $"https://login.windows.net/{tenantID}/", $"https://login.microsoft.com/{tenantID}/", $"https://sts.windows.net/{tenantID}/" }; var scope = settings.Scope; services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.Authority = authority; options.Audience = audience; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuers = validissuers, RequireExpirationTime = true, ValidateLifetime = true, IssuerSigningKeys = openIdConfig.SigningKeys, }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { // TODO WTS: This event is invoked if there where errors during token validation, // please handle as appropriate to your scenario. return(Task.CompletedTask); } }; }); // Add Authorization with claim policy services.AddAuthorization(config => { config.AddPolicy("SampleClaimPolicy", policy => policy .RequireAuthenticatedUser() .RequireClaim("http://schemas.microsoft.com/identity/claims/scope", scope)); }); return(services); }
public UpdateUserResponse UpdateUser(UpdateUserRequest request) { var user = FindUserByName(request.UserDetail.UserName); // update user account info var assembler = new UserAssembler(); assembler.UpdateUser(user, request.UserDetail, PersistenceContext); // reset password if requested if (request.UserDetail.ResetPassword) { var settings = new AuthenticationSettings(); user.ResetPassword(settings.DefaultTemporaryPassword); } PersistenceContext.SynchState(); return new UpdateUserResponse(assembler.GetUserSummary(user)); }