public IdentityCookieOptions() { // Configure all of the cookie middlewares ApplicationCookie = new CookieAuthenticationOptions { AuthenticationScheme = DefaultApplicationScheme, AutomaticAuthenticate = true, AutomaticChallenge = true, LoginPath = new PathString("/Account/Login"), Events = new CookieAuthenticationEvents { OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync } }; ExternalCookie = new CookieAuthenticationOptions { AuthenticationScheme = DefaultExternalScheme, CookieName = DefaultExternalScheme, ExpireTimeSpan = TimeSpan.FromMinutes(5) }; TwoFactorRememberMeCookie = new CookieAuthenticationOptions { AuthenticationScheme = DefaultTwoFactorRememberMeScheme, CookieName = DefaultTwoFactorRememberMeScheme }; TwoFactorUserIdCookie = new CookieAuthenticationOptions { AuthenticationScheme = DefaultTwoFactorUserIdScheme, CookieName = DefaultTwoFactorUserIdScheme, ExpireTimeSpan = TimeSpan.FromMinutes(5) }; }
public void Configure(IApplicationBuilder app, CommonService service) { var authOptions = new CookieAuthenticationOptions { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, AutomaticAuthenticate = true, AutomaticChallenge = true, ExpireTimeSpan = TimeSpan.FromHours(5), Events = new CookieAuthenticationEvents { OnRedirectToLogin = context => { context.Response.StatusCode = (int) HttpStatusCode.Unauthorized; return Task.CompletedTask; } } }; // redirect to setup until configured app.MapWhen( ctx => ctx.Request.Path == "/" && !service.IsConfigured(), req => req.Run( ctx => Task.Run(() => ctx.Response.Redirect("/setup")) ) ); app.UseDefaultFiles() .UseStaticFiles() .UseCookieAuthentication(authOptions) .UseMvc(); CreateDatabase(app); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <param name="properties"></param> /// <param name="cookieOptions"></param> public CookieSigningOutContext( HttpContext context, CookieAuthenticationOptions options, AuthenticationProperties properties, CookieOptions cookieOptions) : base(context, options) { CookieOptions = cookieOptions; Properties = properties; }
/// <summary> /// Creates a new instance of the context object. /// </summary> /// <param name="context">The HTTP request context</param> /// <param name="options">The middleware options</param> /// <param name="authenticationScheme">Initializes AuthenticationScheme property</param> /// <param name="principal">Initializes Principal property</param> /// <param name="properties">Initializes Properties property</param> public CookieSignedInContext( HttpContext context, CookieAuthenticationOptions options, string authenticationScheme, ClaimsPrincipal principal, AuthenticationProperties properties) : base(context, options) { AuthenticationScheme = authenticationScheme; Principal = principal; Properties = properties; }
/// <summary> /// Default constructor for AD Cookie Options. Internally instantiates CookieAuthenticationOptions with default values. /// </summary> public ActiveDirectoryCookieOptions() { // Configure all of the cookie middlewares ApplicationCookie = new CookieAuthenticationOptions { AuthenticationScheme = ApplicationCookieAuthenticationScheme, AutomaticAuthenticate = true, AutomaticChallenge = true, ReturnUrlParameter = "ReturnUrl", LoginPath = new PathString("/windowsauthentication/ntlm"), }; }
public BaseCookieContext( HttpContext context, CookieAuthenticationOptions options) : base(context) { if (options == null) { throw new ArgumentNullException(nameof(options)); } Options = options; }
/// <summary> /// Adds the <see cref="CookieAuthenticationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables cookie authentication capabilities. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="options">A <see cref="CookieAuthenticationOptions"/> that specifies options for the middleware.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, CookieAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return app.UseMiddleware<CookieAuthenticationMiddleware>(Options.Create(options)); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); //app.UseCookieAuthentication(new CookieAuthenticationOptions()); var options_cookie = new CookieAuthenticationOptions { CookieManager = new SystemWebCookieManager() }; app.UseCookieAuthentication(options_cookie); var options = new WsFederationAuthenticationOptions { Wtrealm = ConfigurationManager.AppSettings["ida:Wtrealm"], MetadataAddress = ConfigurationManager.AppSettings["ida:ADFSMetadata"], // optional for customization and adding AD groups to the token in case they are omitted by ADFS Notifications = new WsFederationAuthenticationNotifications() { SecurityTokenValidated = async notification => { var upn = notification.AuthenticationTicket.Identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Upn).Value; using (var principalContext = new PrincipalContext(ContextType.Domain, "UTAD")) { using (var user = UserPrincipal.FindByIdentity(principalContext, upn)) { var groups = user.GetGroups().Select(group => new Claim(ClaimTypes.Role, group.Name)); notification.AuthenticationTicket.Identity.AddClaims(groups); //Removing the claim NAme which gives full name and adding UTAD for name var claim = notification.AuthenticationTicket.Identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name); if (claim != null) { notification.AuthenticationTicket.Identity.RemoveClaim(claim); } notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, user.SamAccountName)); } } await Task.CompletedTask; } } }; app.UseWsFederationAuthentication(options); }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { //Trust all certificates System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); //// trust sender //System.Net.ServicePointManager.ServerCertificateValidationCallback // = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName")); //// validate cert by calling a function //System.Net.ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); //app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType); var cookieAuthOptions = new CookieAuthenticationOptions(); app.UseCookieAuthentication(cookieAuthOptions); //app.UseCookieAuthentication(new CookieAuthenticationOptions //{ // AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType //}); var wsFedPassiveAuthOptions = new WsFederationAuthenticationOptions { MetadataAddress = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"], Wtrealm = ConfigurationManager.AppSettings["ida:Audience"], }; //// Azure Ws-Fed Passive federated authentication support app.UseWsFederationAuthentication(wsFedPassiveAuthOptions); // app.UseActiveDirectoryFederationServicesBearerAuthentication( // new ActiveDirectoryFederationServicesBearerAuthenticationOptions // { // MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"], // TokenValidationParameters = new TokenValidationParameters() // { // ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] // } // }); }
/// <summary> /// Adds the <see cref="CookieAuthenticationMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables cookie authentication capabilities. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param> /// <param name="configureOptions">An action delegate to configure the provided <see cref="CookieAuthenticationOptions"/>.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, Action <CookieAuthenticationOptions> configureOptions) { if (app == null) { throw new ArgumentNullException(nameof(app)); } var options = new CookieAuthenticationOptions(); if (configureOptions != null) { configureOptions(options); } return(app.UseCookieAuthentication(options)); }
public SessionManager( IOptions <IdentityServiceOptions> options, IOptions <IdentityOptions> identityOptions, IOptionsSnapshot <CookieAuthenticationOptions> cookieOptions, ITimeStampManager timeStampManager, IHttpContextAccessor contextAccessor, ProtocolErrorProvider errorProvider) { _options = options; _identityOptions = identityOptions; _timeStampManager = timeStampManager; _contextAccessor = contextAccessor; _errorProvider = errorProvider; _sessionCookieOptions = cookieOptions.Get(IdentityServiceOptions.CookieAuthenticationScheme); }
public void Configuration(IAppBuilder app) { AreaRegistration.RegisterAllAreas(); // RouteConfig.RegisterRoutes(RouteTable.Routes); var option = new CookieAuthenticationOptions() { AuthenticationType = "ApplicationCookie", CookieName = "Logging", LoginPath = new PathString("/LoginAuth/Login") }; app.UseCookieAuthentication(option); }
public void options(CookieAuthenticationOptions options) { options.LoginPath = "/Security/Login"; options.LogoutPath = "/Security/Logout"; options.AccessDeniedPath = "/Security/AccessDenied"; options.SlidingExpiration = true; options.Cookie = new CookieBuilder { HttpOnly = true, Name = "AspNetCoreDemo.Security.Cookie", Path = "/", SameSite = SameSiteMode.Lax, SecurePolicy = CookieSecurePolicy.SameAsRequest }; }
public void Configuration(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll); var options = new CookieAuthenticationOptions() { CookieName = "Token" }; app.UseCookieAuthentication(options); app.Use <CustomLoginMiddleware>(); app.MapSignalR(new HubConfiguration() { EnableDetailedErrors = true }); }
public CookieAuthenticationOptions ToOptions() { var options = new CookieAuthenticationOptions(); base.ToOptions(options); options.SlidingExpiration = SlidingExpiration ?? options.SlidingExpiration; options.LoginPath = LoginPath ?? options.LoginPath; options.LogoutPath = LogoutPath ?? options.LogoutPath; options.AccessDeniedPath = AccessDeniedPath ?? options.AccessDeniedPath; options.ReturnUrlParameter = ReturnUrlParameter ?? options.ReturnUrlParameter; options.ExpireTimeSpan = ExpireTimeSpan ?? options.ExpireTimeSpan; return(options); }
private void SetupOtherCookies(CookieAuthenticationOptions options, string scheme, SiteSettings tenant) { if (multiTenantOptions.UseRelatedSitesMode) { options.AuthenticationScheme = scheme; options.CookieName = scheme; options.CookiePath = "/"; } else { options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}"; options.CookieName = $"{scheme}-{tenant.SiteFolderName}"; options.CookiePath = "/" + tenant.SiteFolderName; } }
public void Configuration(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Auth/Login") }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); app.UseGoogleAuthentication(ConfigurationManager.AppSettings["GoogleClientId"], ConfigurationManager.AppSettings["GoogleClientSecret"]); }
static Startup() { PublicClientId = "self"; IdentityManagerFactory = new IdentityManagerFactory(IdentityConfig.Settings, () => new IdentityStore()); CookieOptions = new CookieAuthenticationOptions(); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = "/Token", AuthorizeEndpointPath = "/api/Account/ExternalLogin", Provider = new ApplicationOAuthProvider(PublicClientId, IdentityManagerFactory, CookieOptions) }; }
private static void SetCookieFormatter(CookieAuthenticationOptions cookieAuthenticationOptions) { if (ConfigurationManager.AppSettings["UseJwtAuthCookie"] == "true") { int parsedDays = 0; if (!int.TryParse(ConfigurationManager.AppSettings["Jwt.ExpirationDays"], out parsedDays)) { parsedDays = 30; } string _jwtSecret; TokenValidationParameters tokenParams; SetTokenValidationParameters(out _jwtSecret, out tokenParams); cookieAuthenticationOptions.TicketDataFormat = new AppJwtFormat(tokenParams, _jwtSecret, parsedDays); } }
// 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, IOptions <SimpleAuthSettings> authSettingsAccessor ) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline SimpleAuthSettings authSettings = authSettingsAccessor.Value; var ApplicationCookie = new CookieAuthenticationOptions { AuthenticationScheme = authSettings.AuthenticationScheme, CookieName = authSettings.AuthenticationScheme, AutomaticAuthenticate = true, AutomaticChallenge = true, LoginPath = new PathString("/Login/Index") }; app.UseCookieAuthentication(ApplicationCookie); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
private void ConfigureAuthentication(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Account/Login") }; cookieOptions.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie; cookieOptions.Provider = new CookieAuthenticationProvider { OnValidateIdentity = OnValidateIdentity }; app.UseCookieAuthentication(cookieOptions); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); SetupGoogleProvider(app); }
public static void AddDefaultCookieEvents(this CookieAuthenticationOptions options) { if (options is null) { return; } options.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = (context) => { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(Task.CompletedTask); } }; }
public void AddCookie(CookieAuthenticationOptions options) { options.Cookie.HttpOnly = true; options.Cookie.Name = Constants.AppName; options.Cookie.SameSite = _env.IsProduction() ? SameSiteMode.Lax : SameSiteMode.None; options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return(Task.FromResult(string.Empty)); }; options.Events.OnRedirectToLogout = context => { context.Response.StatusCode = 200; return(Task.FromResult(string.Empty)); }; }
//public LocalTokenAuthenticationOptions() // : base(CookieAuthenticationDefaults.AuthenticationType) //{ // TokenEndpoint = new PathString("/get_token"); // CallbackTokenParameter = "token"; //} public LocalTokenAuthenticationOptions(CookieAuthenticationOptions cookieOptions) : base(cookieOptions.AuthenticationType) { TokenEndpoint = new PathString("/get_token"); CallbackTokenParameter = "access_token"; ReturnUrlParameter = "redirect_uri"; CookieManager = cookieOptions.CookieManager; SessionStore = cookieOptions.SessionStore; TicketDataFormat = cookieOptions.TicketDataFormat; CookieName = cookieOptions.CookieName; SystemClock = cookieOptions.SystemClock; ClientHostsWhitelists = new List <string>() { "*" }; }
public void ConfigureAuth(IAppBuilder app) { CookieAuthenticationOptions options = new CookieAuthenticationOptions() { AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, LoginPath = new PathString(AccountLoginPath), LogoutPath = new PathString(AccountLogoutPath), }; app.UseCookieAuthentication(options); app.Use(async(context, next) => { await AccountAuth(context, next); }); }
private void SetCookieOptions(CookieAuthenticationOptions options) { options.Cookie.Name = "auth-token"; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.LoginPath = Configuration["Basic:LoginPath"]; options.AccessDeniedPath = Configuration["Basic:AccessDeniedPath"]; options.LogoutPath = Configuration["Basic:LogoutPath"]; options.ClaimsIssuer = Configuration["Basic:ClaimIssuer"]; options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { if (context.Principal.Identity.IsAuthenticated) { var props = context.Properties; // check for out of date web token or missing token if (!await RefreshWebToken(props)) { context.RejectPrincipal(); await context.HttpContext.SignOutAsync( CookieAuthenticationDefaults.AuthenticationScheme); return; } else { if (props.IssuedUtc < DateTime.UtcNow.AddHours(-2) || string.IsNullOrEmpty(props.GetTokenValue("api_token"))) { if (await RefreshApiToken(props)) { context.ShouldRenew = true; } } } if (HttpClientHelper.ClientUser().LoginState != Discord.LoginState.LoggedIn) { //await HttpClientHelper.DiscordClientUserLoginAsync(context.Properties.GetTokenValue("access_token")); } await HttpClientHelper.DiscordClientBotLoginAsync(); } } }; options.Validate(); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); var authProvider = new CookieAuthenticationProvider { OnResponseSignIn = ctx => { //ctx.Identity = StartupAuth.InitAuth(ctx); } }; var cookieOptions = new CookieAuthenticationOptions { Provider = authProvider }; app.UseCookieAuthentication(cookieOptions); // Required for AAD OpenIdConnectAuthenticationOptions Options = new OpenIdConnectAuthenticationOptions { Authority = string.Format(aadInstance, tenant), ClientId = clientId, //ProtocolValidator = new OpenIdConnectProtocolValidator //{ // RequireNonce = false //}, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = AuthenticationFailed, RedirectToIdentityProvider = (context) => { string appBaseUrl = string.Format("{0}://{1}{2}", context.Request.Scheme, context.Request.Host, context.Request.PathBase); context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + "/Account/SignedOut"; return(Task.FromResult(0)); }, }, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, }, AuthenticationType = CustomAuthTypes.B2E, }; app.UseOpenIdConnectAuthentication(Options); }
public static void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); var option = new CookieAuthenticationOptions() { AuthenticationType = "ApplicationCookie", CookieName = "Admin", LoginPath = new PathString("/Auth/Login") }; app.UseCookieAuthentication(option); app.UseGoogleAuthentication( clientId: "943878812622-3esrgkg1puv20cof6fjb1ki2avg0olca.apps.googleusercontent.com", clientSecret: "4500pxs_te6vnibut43bugc6"); }
private void ConfigureAuth(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString(_loginPath) }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { ClientId = _clientId, ClientSecret = _clientSecret, }); }
private void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie CookieAuthenticationOptions cookieOpt = new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, AuthenticationMode = AuthenticationMode.Active, SlidingExpiration = true, ExpireTimeSpan = TimeSpan.FromMinutes(525600), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <CustomUserManager, CustomUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie)), OnApplyRedirect = ctx => { if (!IsAjaxRequest(ctx.Request)) { ctx.Response.Redirect(ctx.RedirectUri); } } } }; if (!Helpers.WebConfigSettings.UseWindowsAuthentication) //no need for any of this part if we're authenticating via windows { cookieOpt.LogoutPath = new PathString("/Account/Logoff"); cookieOpt.LoginPath = new PathString("/Account/LogOn"); app.UseCookieAuthentication(cookieOpt); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); } }
private void ConfigureAuth(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Account/Login") }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { ClientId = ConfigurationManager.AppSettings["ClientId"], ClientSecret = ConfigurationManager.AppSettings["ClientSecret"] }); }
/// <summary> /// Adds a cookie-based authentication middleware to your web application pipeline. /// </summary> /// <param name="app">The IApplicationBuilder passed to your configuration method</param> /// <param name="configureOptions">Used to configure the options for the middleware</param> /// <param name="optionsName">The name of the options class that controls the middleware behavior, null will use the default options</param> /// <returns>The original app parameter</returns> //public static IApplicationBuilder UseMultiTenantCookieAuthentication( // this IApplicationBuilder app, // Action<CookieAuthenticationOptions> configureOptions = null, // string optionsName = "") //{ // return app.UseMiddleware<MultiTenantCookieAuthenticationMiddleware>( // new ConfigureOptions<CookieAuthenticationOptions>(configureOptions ?? (o => { })) // { // Name = optionsName // }); //} public static IApplicationBuilder UseMultiTenantCookieAuthentication( this IApplicationBuilder app, CookieAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return(app.UseMiddleware <MultiTenantCookieAuthenticationMiddleware>(options)); }
public static CookieAuthenticationOptions ConfigureSessionStorage(this CookieAuthenticationOptions opts, IWebSessionSettings settings) { if (settings.SessionStorage == SessionStorageType.InMemory) { opts.SessionStore = new InMemoryTicketStore(settings); } else if (settings.SessionStorage == SessionStorageType.Redis) { var connectionString = settings.RedisConnectionString().GetAwaiter().GetResult(); opts.SessionStore = new RedisTicketStore(new RedisCacheOptions { Configuration = connectionString, InstanceName = CacheModule.RedisInstanceName }, settings); } return(opts); }
public void ShouldSetAccessDeniedPath() { var authOptions = new AuthOptions { AccessDeniedPath = "accessdenied" }; var mockTokenRefreshHandler = new Mock <ITokenRefreshHandler>(); var cookieOptionsFactory = new CookieOptionsFactory(mockTokenRefreshHandler.Object, Options.Create(authOptions)); var options = new CookieAuthenticationOptions(); cookieOptionsFactory.Setup(options); Assert.Equal($"/{authOptions.AccessDeniedPath}", options.AccessDeniedPath); }
private static void SetCookieFormatter(CookieAuthenticationOptions cookieAuthenticationOptions) { // No need to ever use this as it is too buggy. //if (ConfigurationManager.AppSettings["UsePlaintextAuthCookie"] == "true") //{ // cookieAuthenticationOptions.TicketDataFormat = new PlaintextSecureDataFormat(); //} if (ConfigurationManager.AppSettings["UseJwtAuthCookie"] == "true") { string _jwtSecret; TokenValidationParameters tokenParams; SetTokenValidationParameters(out _jwtSecret, out tokenParams); cookieAuthenticationOptions.TicketDataFormat = new AppJwtFormat(tokenParams, _jwtSecret); } }
private static TestServer CreateServer(CookieAuthenticationOptions options, Func <IOwinContext, Task> testpath = null) { return(TestServer.Create(app => { app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests"; app.UseCookieAuthentication(options); app.Use(async(context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; PathString remainder; if (req.Path == new PathString("/normal")) { res.StatusCode = 200; } else if (req.Path == new PathString("/protected")) { res.StatusCode = 401; } else if (req.Path == new PathString("/protected/CustomRedirect")) { context.Authentication.Challenge(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" }); } else if (req.Path == new PathString("/me")) { Describe(res, new AuthenticateResult(req.User.Identity, new AuthenticationProperties(), new AuthenticationDescription())); } else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) { AuthenticateResult result = await context.Authentication.AuthenticateAsync(remainder.Value.Substring(1)); Describe(res, result); } else if (req.Path == new PathString("/testpath") && testpath != null) { await testpath(context); } else { await next(); } }); })); }
private void SamlConfiguration(IAppBuilder app) { var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/Account/Login"), AuthenticationType = "Application", AuthenticationMode = AuthenticationMode.Passive }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); app.UseSaml2Authentication(CreateSaml2Options()); app.UseStageMarker(PipelineStage.Authenticate); }
/// <summary> /// Creates a new instance of the context object. /// </summary> /// <param name="context"></param> /// <param name="ticket">Contains the initial values for identity and extra data</param> /// <param name="options"></param> public CookieValidatePrincipalContext(HttpContext context, AuthenticationTicket ticket, CookieAuthenticationOptions options) : base(context, options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (ticket == null) { throw new ArgumentNullException(nameof(ticket)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } Principal = ticket.Principal; Properties = ticket.Properties; }
/// <summary> /// Constructor accepting CookieAuthenticationOptions /// </summary> /// <param name="cookieOptions"></param> public ActiveDirectoryCookieOptions(CookieAuthenticationOptions cookieOptions) { // Configure all of the cookie middlewares ApplicationCookie = cookieOptions; }
private CookieAuthenticationOptions SetupOtherCookies( string scheme, bool useRelatedSitesMode, cloudscribe.Core.Models.SiteSettings tenant ) { var options = new CookieAuthenticationOptions(); if(useRelatedSitesMode) { options.AuthenticationScheme = scheme; options.CookieName = scheme; options.CookiePath = "/"; } else { options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}"; options.CookieName = $"{scheme}-{tenant.SiteFolderName}"; options.CookiePath = "/" + tenant.SiteFolderName; } return options; }
private CookieAuthenticationOptions SetupAppCookie( CookieAuthenticationEvents cookieEvents, cloudscribe.Core.Identity.SiteAuthCookieValidator siteValidator, string scheme, bool useRelatedSitesMode, cloudscribe.Core.Models.SiteSettings tenant ) { var options = new CookieAuthenticationOptions(); if(useRelatedSitesMode) { options.AuthenticationScheme = scheme; options.CookieName = scheme; options.CookiePath = "/"; } else { options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}"; options.CookieName = $"{scheme}-{tenant.SiteFolderName}"; options.CookiePath = "/" + tenant.SiteFolderName; cookieEvents.OnValidatePrincipal = siteValidator.ValidatePrincipal; } var tenantPathBase = string.IsNullOrEmpty(tenant.SiteFolderName) ? PathString.Empty : new PathString("/" + tenant.SiteFolderName); options.LoginPath = tenantPathBase + "/account/login"; options.LogoutPath = tenantPathBase + "/account/logoff"; options.Events = cookieEvents; options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; return options; }
// 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 ) { //app.UseSession(); loggerFactory.AddConsole(Configuration.GetSection("Logging")); if (env.IsDevelopment()) { loggerFactory.AddDebug(LogLevel.Information); app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { loggerFactory.AddDebug(LogLevel.Debug); app.UseExceptionHandler("/Home/Error"); try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { serviceScope.ServiceProvider.GetService<CronicaDbContext>() .Database.Migrate(); } } catch { } } app.UseStaticFiles(); app.UseIdentity(); CookieAuthenticationOptions cookiesOptions = new CookieAuthenticationOptions(); cookiesOptions.AuthenticationScheme = "Cookies"; cookiesOptions.LogoutPath = new PathString("/Home/Index"); cookiesOptions.LoginPath = new PathString("/Home/Index"); cookiesOptions.AccessDeniedPath = new PathString("/Home/Index"); cookiesOptions.CookieName = "VerumInSanguine"; app.UseCookieAuthentication(cookiesOptions); var ci = new CultureInfo("es-ES"); ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy"; RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions(); localizationOptions.DefaultRequestCulture = new RequestCulture(ci); localizationOptions.SupportedCultures.Add(ci); localizationOptions.SupportedUICultures.Add(ci); app.UseRequestLocalization(localizationOptions); ConfigurarRutas(app); }
// 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.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); var ApplicationCookie = new CookieAuthenticationOptions { AuthenticationScheme = "application", CookieName = "application", AutomaticAuthenticate = true, AutomaticChallenge = true, LoginPath = new PathString("/FakeAccount/Index"), Events = new CookieAuthenticationEvents { //OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync } }; app.UseCookieAuthentication(ApplicationCookie); app.UseMvc(routes => { routes.MapRoute("areaRoute", "{area:exists}/{controller=Roswell}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public static CookieAuthenticationOptions SetupAppCookie( this IApplicationBuilder app, SiteAuthCookieValidator siteValidator, string scheme, bool useRelatedSitesMode, SiteContext tenant, CookieSecurePolicy cookieSecure = CookieSecurePolicy.SameAsRequest ) { var cookieEvents = new CookieAuthenticationEvents(); var options = new CookieAuthenticationOptions(); if (useRelatedSitesMode) { options.AuthenticationScheme = scheme; options.CookieName = scheme; options.CookiePath = "/"; } else { //options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}"; options.AuthenticationScheme = scheme; options.CookieName = $"{scheme}-{tenant.SiteFolderName}"; options.CookiePath = "/" + tenant.SiteFolderName; cookieEvents.OnValidatePrincipal = siteValidator.ValidatePrincipal; } var tenantPathBase = string.IsNullOrEmpty(tenant.SiteFolderName) ? PathString.Empty : new PathString("/" + tenant.SiteFolderName); options.LoginPath = tenantPathBase + "/account/login"; options.LogoutPath = tenantPathBase + "/account/logoff"; options.AccessDeniedPath = tenantPathBase + "/account/accessdenied"; options.Events = cookieEvents; options.AutomaticAuthenticate = true; options.AutomaticChallenge = false; options.CookieSecure = cookieSecure; return options; }
public static CookieAuthenticationOptions SetupOtherCookies( this IApplicationBuilder app, string scheme, bool useRelatedSitesMode, SiteContext tenant, CookieSecurePolicy cookieSecure = CookieSecurePolicy.None ) { var options = new CookieAuthenticationOptions(); if (useRelatedSitesMode) { options.AuthenticationScheme = scheme; options.CookieName = scheme; options.CookiePath = "/"; } else { //options.AuthenticationScheme = $"{scheme}-{tenant.SiteFolderName}"; options.AuthenticationScheme = scheme; options.CookieName = $"{scheme}-{tenant.SiteFolderName}"; options.CookiePath = "/" + tenant.SiteFolderName; } options.AutomaticAuthenticate = false; if (cookieSecure != CookieSecurePolicy.None) { options.CookieSecure = cookieSecure; } return options; }
public static IApplicationBuilder UseSocialAuth( this IApplicationBuilder app, SiteContext site, CookieAuthenticationOptions externalCookieOptions, bool shouldUseFolder) { // TODO: will this require a restart if the options are updated in the ui? // no just need to clear the tenant cache after updating the settings if (!string.IsNullOrWhiteSpace(site.GoogleClientId)) { var googleOptions = new GoogleOptions(); googleOptions.AuthenticationScheme = "Google"; googleOptions.SignInScheme = externalCookieOptions.AuthenticationScheme; googleOptions.ClientId = site.GoogleClientId; googleOptions.ClientSecret = site.GoogleClientSecret; if (shouldUseFolder) { googleOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-google"; } app.UseGoogleAuthentication(googleOptions); } if (!string.IsNullOrWhiteSpace(site.FacebookAppId)) { var facebookOptions = new FacebookOptions(); facebookOptions.AuthenticationScheme = "Facebook"; facebookOptions.SignInScheme = externalCookieOptions.AuthenticationScheme; facebookOptions.AppId = site.FacebookAppId; facebookOptions.AppSecret = site.FacebookAppSecret; if (shouldUseFolder) { facebookOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-facebook"; } app.UseFacebookAuthentication(facebookOptions); } if (!string.IsNullOrWhiteSpace(site.MicrosoftClientId)) { var microsoftOptions = new MicrosoftAccountOptions(); microsoftOptions.SignInScheme = externalCookieOptions.AuthenticationScheme; microsoftOptions.ClientId = site.MicrosoftClientId; microsoftOptions.ClientSecret = site.MicrosoftClientSecret; if (shouldUseFolder) { microsoftOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-microsoft"; } app.UseMicrosoftAccountAuthentication(microsoftOptions); } //app.Use() //Func<HttpContext, bool> hasTwitterKeys = (HttpContext context) => //{ // var tenant = context.GetTenant<SiteSettings>(); // if (tenant == null) return false; // if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerKey)) return false; // if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerSecret)) return false; // return true; //}; //app.UseWhen(context => hasTwitterKeys(context), appBuilder => //{ if (!string.IsNullOrWhiteSpace(site.TwitterConsumerKey)) { var twitterOptions = new TwitterOptions(); twitterOptions.SignInScheme = externalCookieOptions.AuthenticationScheme; twitterOptions.ConsumerKey = site.TwitterConsumerKey; twitterOptions.ConsumerSecret = site.TwitterConsumerSecret; if (shouldUseFolder) { twitterOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-twitter"; } app.UseTwitterAuthentication(twitterOptions); } //}); return app; }
private static TestServer CreateServer(CookieAuthenticationOptions options, Func<HttpContext, Task> testpath = null, Uri baseAddress = null, ClaimsTransformationOptions claimsTransform = null) { var builder = new WebHostBuilder() .Configure(app => { app.UseCookieAuthentication(options); // app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie2" }); if (claimsTransform != null) { app.UseClaimsTransformation(claimsTransform); } app.Use(async (context, next) => { var req = context.Request; var res = context.Response; PathString remainder; if (req.Path == new PathString("/normal")) { res.StatusCode = 200; } else if (req.Path == new PathString("/protected")) { res.StatusCode = 401; } else if (req.Path == new PathString("/forbid")) // Simulate forbidden { await context.Authentication.ForbidAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/challenge")) { await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/signout")) { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } else if (req.Path == new PathString("/unauthorized")) { await context.Authentication.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties(), ChallengeBehavior.Unauthorized); } else if (req.Path == new PathString("/protected/CustomRedirect")) { await context.Authentication.ChallengeAsync(new AuthenticationProperties() { RedirectUri = "/CustomRedirect" }); } else if (req.Path == new PathString("/me")) { var authContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme); authContext.Authenticated(context.User, properties: null, description: null); Describe(res, authContext); } else if (req.Path.StartsWithSegments(new PathString("/me"), out remainder)) { var authContext = new AuthenticateContext(remainder.Value.Substring(1)); await context.Authentication.AuthenticateAsync(authContext); Describe(res, authContext); } else if (req.Path == new PathString("/testpath") && testpath != null) { await testpath(context); } else { await next(); } }); }) .ConfigureServices(services => services.AddAuthentication()); var server = new TestServer(builder); server.BaseAddress = baseAddress; return server; }
/// <summary> /// Creates a new context object. /// </summary> /// <param name="context">The HTTP request context</param> /// <param name="options">The cookie middleware options</param> /// <param name="redirectUri">The initial redirect URI</param> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> public CookieRedirectContext(HttpContext context, CookieAuthenticationOptions options, string redirectUri, AuthenticationProperties properties) : base(context, options) { RedirectUri = redirectUri; Properties = properties; }