public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppIdentityDbContext>(opts => { opts.UseSqlServer(_configuration["ConnectionStrings:DefaultConnectionStrings"]); }); services.AddIdentity <AppUser, IdentityRole>(opts => { opts.Password.RequiredLength = 5; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; opts.Password.RequireDigit = false; }).AddEntityFrameworkStores <AppIdentityDbContext>().AddDefaultTokenProviders(); CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "MyBlog"; cookieBuilder.HttpOnly = false; cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.ExpireTimeSpan = System.TimeSpan.FromDays(20); //opts.Cookie.Expiration = System.TimeSpan.FromDays(20); opts.LoginPath = new PathString("/Home/Login"); opts.Cookie = cookieBuilder; opts.SlidingExpiration = true; }); services.AddMvc(); services.AddControllersWithViews(); }
private static void SetCookieFromConfig(IConfiguration cookieConfigSection, CookieBuilder cookieBuilder) { if (cookieConfigSection is null || !cookieConfigSection.GetChildren().Any()) { return; } // Override the existing defaults when values are set instead of constructing // an entirely new CookieBuilder. cookieBuilder.Domain = cookieConfigSection[nameof(cookieBuilder.Domain)] ?? cookieBuilder.Domain; cookieBuilder.HttpOnly = StringHelpers.ParseValueOrDefault(cookieConfigSection[nameof(cookieBuilder.HttpOnly)], bool.Parse, cookieBuilder.HttpOnly); cookieBuilder.IsEssential = StringHelpers.ParseValueOrDefault(cookieConfigSection[nameof(cookieBuilder.IsEssential)], bool.Parse, cookieBuilder.IsEssential); cookieBuilder.Expiration = StringHelpers.ParseValueOrDefault(cookieConfigSection[nameof(cookieBuilder.Expiration)], _invariantNullableTimeSpanParse, cookieBuilder.Expiration); cookieBuilder.MaxAge = StringHelpers.ParseValueOrDefault <TimeSpan?>(cookieConfigSection[nameof(cookieBuilder.MaxAge)], _invariantNullableTimeSpanParse, cookieBuilder.MaxAge); cookieBuilder.Name = cookieConfigSection[nameof(CookieBuilder.Name)] ?? cookieBuilder.Name; cookieBuilder.Path = cookieConfigSection[nameof(CookieBuilder.Path)] ?? cookieBuilder.Path; cookieBuilder.SameSite = cookieConfigSection[nameof(CookieBuilder.SameSite)] is string sameSiteMode ? Enum.Parse <SameSiteMode>(sameSiteMode, ignoreCase : true) : cookieBuilder.SameSite; cookieBuilder.SecurePolicy = cookieConfigSection[nameof(CookieBuilder.SecurePolicy)] is string securePolicy ? Enum.Parse <CookieSecurePolicy>(securePolicy, ignoreCase : true) : cookieBuilder.SecurePolicy; ClearAndSetListOption(cookieBuilder.Extensions, cookieConfigSection.GetSection(nameof(cookieBuilder.Extensions))); }
public CookieBuilder Build() { CookieBuilder builder = new CookieBuilder() { Name = cookieName ?? DEFAULT_COOKIE_NAME, Path = cookiePath ?? DEFAULT_COOKIE_PATH, Expiration = TimeSpan.FromSeconds(cookieTimeout ?? DEFAULT_COOKIE_TIMEOUT_SECONDS), //Expires = DateTime.UtcNow.AddSeconds(cookieTimeout ?? DEFAULT_COOKIE_TIMEOUT_SECONDS), SecurePolicy = cookieSecurePolicy ?? DEFAULT_SECURE_POLICY }; //AnonymousIdCookieOptions options = new AnonymousIdCookieOptions //{ // Name = cookieName ?? DEFAULT_COOKIE_NAME, // Path = cookiePath ?? DEFAULT_COOKIE_PATH, // Timeout = cookieTimeout ?? DEFAULT_COOKIE_TIMEOUT_SECONDS, // Expires = DateTime.UtcNow.AddSeconds(cookieTimeout ?? DEFAULT_COOKIE_TIMEOUT), // Secure = cookieSecurePolicy ?? DEFAULT_SECURE_POLICY //}; if (!string.IsNullOrWhiteSpace(cookieDomain)) { builder.Domain = cookieDomain; } return(builder); }
public DiscourseAuthenticationOptions() { CallbackPath = "/auth-discourse"; _nonceCookieBuilder = new DiscourseNonceCookieBuilder(this) { Name = ".CitizenFX.Discourse.Nonce.", HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest, IsEssential = true, }; DataProtectionProvider = Microsoft.AspNetCore.DataProtection.DataProtectionProvider.Create("FXServer"); var dataProtector = DataProtectionProvider.CreateProtector( typeof(DiscourseAuthenticationHandler).FullName, typeof(string).FullName, "DAO", "v1"); StringDataFormat = new SecureDataFormat <string>(new StringSerializer(), dataProtector); StateDataFormat = new PropertiesDataFormat(dataProtector); }
public void ConfigureCookieOptions(CookieBuilder cookieBuilder) { cookieBuilder.HttpOnly = true; cookieBuilder.IsEssential = true; cookieBuilder.MaxAge = TimeSpan.FromMinutes(ApplicationSettings.CookieExpiryPeriodInMinutes); cookieBuilder.SameSite = SameSiteMode.Strict; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; }
/// <summary> /// Register cookie authentication related actors /// </summary> /// <remarks> /// Remember to configure 'UseCookieAuthentication()' and 'UseAuthorization()' /// after 'UseRouting()', but before 'UseEndpoints()' /// </remarks> /// <param name="services"></param> /// <param name="configRoot"></param> /// <param name="mode"></param> public static AuthenticationBuilder AddCookieAuthentication( this IServiceCollection services, IConfigurationRoot configRoot, SameSiteMode mode = SameSiteMode.Lax ) { var config = configRoot .GetSection(WebConfiguration.AUTHENTICATION) .GetSection(WebConfiguration.AUTHENTICATION_COOKIE) .Get <CookieAuthenticationConfiguration>(); if (config == null) { var configPath = $"{WebConfiguration.AUTHENTICATION}:{WebConfiguration.AUTHENTICATION_COOKIE}"; throw new Exception($"Unable to find configuration for '{configPath}' <CookieAuthenticationConfiguration>"); } var cookie = new CookieBuilder { Name = config.CookieName, SameSite = mode }; var cookieEvents = new CookieAuthenticationEvents { OnRedirectToAccessDenied = context => { context.Response.StatusCode = 403; // Don't redirect, set to forbidden return(Task.CompletedTask); }, OnRedirectToLogin = context => { context.Response.StatusCode = 401; // Don't redirect, set to unauthorized return(Task.CompletedTask); } }; services.AddSingleton((sp) => config); // Register actors return(services .AddAuthentication((options) => { options.DefaultAuthenticateScheme = options.DefaultChallengeScheme = options.DefaultScheme = options.DefaultSignInScheme = config.AuthenticationScheme; }) .AddCookie(config.AuthenticationScheme, options => { options.AccessDeniedPath = new PathString(config.AccessDeniedPath); options.Cookie = cookie; options.Events = cookieEvents; options.LoginPath = new PathString(config.LoginPath); })); }
/// <summary> /// Initializes a new <see cref="RemoteAuthenticationOptions"/>. /// </summary> public RemoteAuthenticationOptions() { _correlationCookieBuilder = new CorrelationCookieBuilder(this) { Name = CorrelationPrefix, HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest, }; }
/// <summary> /// Initializes a new instance of the <see cref="Saml2Options" /> class. /// </summary> public Saml2Options() { EnablePIILogging = false; WantAuthnRequestsSigned = false; ForwardChallenge = AuthenticationScheme; SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; SignOutScheme = AuthenticationScheme; AuthenticationScheme = Saml2Defaults.AuthenticationScheme; SignOutPath = new PathString("/signedout"); CallbackPath = new PathString("/saml2-signin"); DefaultRedirectUrl = new PathString("/"); RequireHttpsMetadata = true; ForceAuthn = true; NameIDType = new NameIDType(); IsPassive = false; VerifySignatureOnly = true; DefaultMetadataFolderLocation = "wwwroot"; DefaultMetadataFileName = "Metadata"; CreateMetadataFile = false; ServiceProvider = new ServiceProviderInfo() { HashAlgorithm = HashAlgorithmName.SHA256, AssertionConsumerServices = new IndexedEndpointType[] { new IndexedEndpointType() { Binding = ProtocolBindings.HTTP_Post, //must only allow POST index = 0, isDefault = true, isDefaultSpecified = true } }, SingleLogoutServices = new EndpointType[] { new EndpointType() { Binding = ProtocolBindings.HTTP_Post //must only allow Post back to sp } } }; WantAssertionsSigned = false; RequireMessageSigned = false; RequestIdCookieLifetime = TimeSpan.FromMinutes(10); RequestCookieId = new CookieBuilder() { IsEssential = CookieConsentNeeded, HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest, Expiration = RequestIdCookieLifetime }; Events = new Saml2Events(); AllowUnsolicitedLogins = false; }
public void ComputesExpiration() { Assert.Null(new CookieBuilder().Build(new DefaultHttpContext()).Expires); var now = DateTimeOffset.Now; var options = new CookieBuilder { Expiration = TimeSpan.FromHours(1) }.Build(new DefaultHttpContext(), now); Assert.Equal(now.AddHours(1), options.Expires); }
public void ComputesMaxAge() { Assert.Null(new CookieBuilder().Build(new DefaultHttpContext()).MaxAge); var now = TimeSpan.FromHours(1); var options = new CookieBuilder { MaxAge = now }.Build(new DefaultHttpContext()); Assert.Equal(now, options.MaxAge); }
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSignalR(); services.AddDbContext <AppIdentityDbContext>(options => { options.UseSqlServer(Configuration["ConnectionStrings:IdentityConnection"]); }); services.AddIdentity <AppUser, AppRole>(opts => { opts.Password.RequireDigit = true; opts.Password.RequireLowercase = true; opts.Password.RequiredLength = 6; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireUppercase = true; opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; }).AddPasswordValidator <CustomPasswordValidator>() .AddUserValidator <CustomUserValidator>() .AddErrorDescriber <CustomIdentityErrorDescriber>() .AddEntityFrameworkStores <AppIdentityDbContext>() .AddDefaultTokenProviders(); CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "MySite"; cookieBuilder.HttpOnly = false; cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.LoginPath = new PathString("/giris"); opts.LogoutPath = new PathString("/cýkýs"); opts.AccessDeniedPath = new PathString("/erisimyok"); opts.Cookie = cookieBuilder; opts.SlidingExpiration = true; opts.ExpireTimeSpan = System.TimeSpan.FromDays(60); }); services.AddDependencyResolvers(new ICoreModule[] { new CoreModule() }); }
public CookieBuilderFilter(CookieBuilder cookieBuilder) { Domain = cookieBuilder.Domain; Expiration = cookieBuilder.Expiration; HttpOnly = cookieBuilder.HttpOnly; IsEssential = cookieBuilder.IsEssential; MaxAge = cookieBuilder.MaxAge; Name = cookieBuilder.Name; Path = cookieBuilder.Path; SameSite = cookieBuilder.SameSite; SecurePolicy = cookieBuilder.SecurePolicy; }
public Task Invoke(HttpContext httpContext) { if (!httpContext.Response.HasStarted) { CookieBuilder cookieBuilder = new CookieBuilder { Name = ".AspNetCore.Culture" }; var cookieOptions = cookieBuilder.Build(httpContext); httpContext.Response.Cookies.Append(cookieBuilder.Name, "c=fr-FR|uic=fr-Fr", cookieOptions); } return(_next(httpContext)); }
public void TestGetCookieValueCreatesAndCallsFunction() { var cookieString = CookieBuilder.GetCookieValue("TestCookie"); var strippedString = Regex.Replace(cookieString, @"\s+", ""); var expectedOutput = "function getCookie(name) {\n" + " var value = \"; \" + document.cookie;\n" + " var parts = value.split(\"; \" + name + \"=\");\n" + " if (parts.length == 2) return parts.pop().split(\";\").shift();\n" + "}\n" + "getCookie('TestCookie')"; var strippedOutput = Regex.Replace(expectedOutput, @"\s+", ""); Assert.AreEqual(strippedOutput, strippedString); }
private static void SetUpCookieAuth(IServiceCollection services, IConfiguration configuration) { //services.Configure<SecurityConfig>(Configuration.GetSection("Security")); //services.Configure<JsonWebTokenConfig>(Configuration.GetSection("JsonWebToken")); SecurityConfig security = new SecurityConfig(); JsonWebTokenConfig jsonWebTokenConfig = new JsonWebTokenConfig(); configuration.GetSection("SecurityConfig").Bind(security); configuration.GetSection("JsonWebTokenConfig").Bind(jsonWebTokenConfig); CookieBuilder cookie = new CookieBuilder(); cookie.Domain = security.AppDomain; cookie.Name = security.CookieName; cookie.HttpOnly = true; cookie.Path = "/"; cookie.SameSite = SameSiteMode.None; cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; cookie.MaxAge = TimeSpan.FromMinutes(60 * 24 * 90); // If you don't want the cookie to be automatically authenticated and assigned to // HttpContext.User, remove the CookieAuthenticationDefaults.AuthenticationScheme // parameter passed to AddAuthentication. services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.Cookie = cookie; options.SlidingExpiration = true; options.TicketDataFormat = new Sabio.Web.Core.Services.TokenSecureDataFormat(jsonWebTokenConfig); options.AccessDeniedPath = "/unauthorized"; options.LoginPath = "/login"; options.LogoutPath = "/logout"; options.Events = new CookieAuthenticationEvents(); options.Events.OnRedirectToAccessDenied = RedirectContext; options.Events.OnRedirectToLogin = RedirectContext; }); services.AddAuthorization(authorizeOptions => { authorizeOptions.AddPolicy("defaultpolicy", b => { b.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme); b.RequireAuthenticatedUser(); }); }); }
public Saml2Options() { DefaultRedirectUrl = "/"; SessionCookieLifetime = TimeSpan.FromMinutes(10); _sessionCookie = new SessionCookieBuilder(this) { Name = $"{Saml2Defaults.SessionKeyPrefix}.{Guid.NewGuid():N}", HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest }; }
public void ConfiguresSecurePolicy(CookieSecurePolicy policy, bool requestIsHttps, bool secure) { var builder = new CookieBuilder { SecurePolicy = policy }; var context = new DefaultHttpContext(); context.Request.IsHttps = requestIsHttps; var options = builder.Build(context); Assert.Equal(secure, options.Secure); }
public void TestCreateCookieWithSemiColonInNameThrowsAnException() { try { CookieBuilder.CreateCookie("Test;Cookie", "Some Value", null, null, null, false); } catch (ArgumentException ex) { StringAssert.Contains(ex.Message, "Cookie name cannot contain ';'"); Assert.AreEqual("name", ex.ParamName); throw; } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <IIlanRepository, EfCoreIlanRepository>(); services.AddScoped <IIlanService, IlanManager>(); services.AddControllersWithViews(); // DB iþlemleri var dataAssemblyName = typeof(EmlakfOfisiContext).Assembly.GetName().Name; var x = Configuration.GetConnectionString("Default"); services.AddDbContext <EmlakfOfisiContext>(options => options.UseNpgsql(Configuration.GetConnectionString("Default"), x => x.MigrationsAssembly(dataAssemblyName))); // Identity iþlemleri services.AddIdentity <User, Role>().AddEntityFrameworkStores <EmlakfOfisiContext>().AddDefaultTokenProviders(); // Identity konfigürasyonlarý, gerekirse diye aþaðýda commentli olarak býraktým. services.Configure <IdentityOptions>( options => { options.Password.RequireDigit = true; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 0; options.Password.RequireNonAlphanumeric = false; //options.Lockout.MaxFailedAccessAttempts = 5; //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.User.RequireUniqueEmail = true; }); // Cookie iþlemleri CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "EmlakOfisi"; cookieBuilder.HttpOnly = false; cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.LoginPath = new PathString("/Home/Login"); opts.LogoutPath = new PathString("/Member/Logout"); opts.Cookie = cookieBuilder; opts.SlidingExpiration = true; opts.ExpireTimeSpan = System.TimeSpan.FromDays(60); opts.AccessDeniedPath = new PathString("/Member/AccessDenied"); }); }
public JiraOptions() { CallbackPath = new PathString(JiraDefaults.CallbackPath); ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "key"); ClaimActions.MapJsonKey(ClaimTypes.Name, "displayName"); ClaimActions.MapJsonKey("urn:jira:self", "self"); _stateCookieBuilder = new JiraCookieBuilder(this) { Name = JiraDefaults.CookieName, SecurePolicy = CookieSecurePolicy.SameAsRequest, HttpOnly = true, SameSite = SameSiteMode.Lax }; }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { var builder = new CookieBuilder(); builder.Name = "WebApplication.Cookies"; builder.HttpOnly = true; builder.SameSite = SameSiteMode.Lax; builder.MaxAge = TimeSpan.FromHours(1); }); services.AddMvc(); services.AddSignalR(); }
/// <summary> /// Initializes a new instance of the <see cref="TwitterOptions"/> class. /// </summary> public TwitterOptions() { CallbackPath = new PathString("/signin-twitter"); BackchannelTimeout = TimeSpan.FromSeconds(60); Events = new TwitterEvents(); ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email); _stateCookieBuilder = new TwitterCookieBuilder(this) { Name = DefaultStateCookieName, SecurePolicy = CookieSecurePolicy.SameAsRequest, HttpOnly = true, SameSite = SameSiteMode.Lax, }; }
public IActionResult OnGet() { var x = DateTime.Now; CookieBuilder cb = new CookieBuilder() { Expiration = new TimeSpan(0, 30, 0), Name = "First cookie" }; // Response.Cookies.Append("Logkey", loged.ToString(), new CookieOptions() // { Expires = new DateTimeOffset(new DateTime(x.Year,x.Month,x.Day,x.Hour+1,0,0))}); // if (!loged) { // return RedirectToPage("/LogInOut/LogIn"); // } //ViewData["loged"] = "You are loged in"; return(Page()); }
public Saml2Options() { AssertionConsumerServiceUrl = "Saml2/AssertionConsumerService"; SingleLogoutServiceUrl = "Saml2/SingleLogoutService"; DefaultRedirectUrl = "/"; SignInScheme = Saml2Defaults.SignInScheme; AuthenticationScheme = Saml2Defaults.AuthenticationScheme; RequestIdCookieLifetime = TimeSpan.FromMinutes(10); _requestIdCookie = new RequestIdCookieBuilder(this) { Name = $"{Saml2Defaults.RequestIdCookiePrefix}.{Guid.NewGuid():N}", HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest }; }
public void ConfigureServices(IServiceCollection services) { services.AddDependencyResolvers(new ICoreModule[] { new CoreModule() }); services.AddDbContext <ExaminationSystemContext>(options => { options.UseLazyLoadingProxies(); options.UseSqlServer(Configuration.GetConnectionString("ExaminationSystem")); }); services.AddIdentity <AppUser, AppRole>(options => { options.Password.RequiredLength = 4; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireDigit = false; options.User.RequireUniqueEmail = true; options.User.AllowedUserNameCharacters = "abcçdefgðhýijklmnopqrsþtuüvwxyzABCÇDEFGÐHIÝJKLMNOPQRSÞTUÜVWXYZ0123456789-._"; }).AddEntityFrameworkStores <ExaminationSystemContext>().AddDefaultTokenProviders(); CookieBuilder cookieBuilder = new CookieBuilder { Name = "ExaminationSystem", HttpOnly = false, SameSite = SameSiteMode.Lax, //güvenlik için Strict SecurePolicy = CookieSecurePolicy.SameAsRequest }; services.ConfigureApplicationCookie(options => { options.LoginPath = new PathString("/Home/Login"); options.LogoutPath = new PathString("/User/SignOut"); options.Cookie = cookieBuilder; options.SlidingExpiration = true; options.ExpireTimeSpan = TimeSpan.FromDays(60); options.AccessDeniedPath = new PathString("/Member/AccessDenied"); }); services.AddMvc(option => { option.EnableEndpointRouting = false; }) .AddFluentValidation(); }
/// <summary> /// Initializes a new instance of the <see cref="OpenstreetmapOptions"/> class. /// </summary> public OpenstreetmapOptions() { CallbackPath = new PathString("/signin-Openstreetmap"); BackchannelTimeout = TimeSpan.FromSeconds(60); Events = new OpenstreetmapEvents(); UseDevelopmentApi = false; ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email); _stateCookieBuilder = new OpenstreetmapCookieBuilder(this) { Name = DefaultStateCookieName, SecurePolicy = CookieSecurePolicy.SameAsRequest, HttpOnly = true, SameSite = SameSiteMode.Lax, }; }
/// <summary> /// Initializes a new <see cref="TrustOptions"/> /// </summary> /// <remarks> /// Defaults: /// <para>AddNonceToRequest: true.</para> /// <para>BackchannelTimeout: 1 minute.</para> /// <para>ProtocolValidator: new <see cref="TrustProtocolValidator"/>.</para> /// <para>RefreshOnIssuerKeyNotFound: true</para> /// <para>ResponseType: <see cref="TrustResponseType.CodeIdToken"/></para> /// <para>Scope: <see cref="TrustScope.OpenIdProfile"/>.</para> /// <para>TokenValidationParameters: new <see cref="TokenValidationParameters"/> with AuthenticationScheme = authenticationScheme.</para> /// <para>UseTokenLifetime: false.</para> /// </remarks> public TrustOptions() { CallbackPath = new PathString("/signin-oidc"); SignedOutCallbackPath = new PathString("/signout-callback-oidc"); RemoteSignOutPath = new PathString("/signout-oidc"); // Events = new TrustEvents(); Scope.Add("openid"); Scope.Add("profile"); ClaimActions.DeleteClaim("nonce"); ClaimActions.DeleteClaim("aud"); ClaimActions.DeleteClaim("azp"); ClaimActions.DeleteClaim("acr"); ClaimActions.DeleteClaim("amr"); ClaimActions.DeleteClaim("iss"); ClaimActions.DeleteClaim("iat"); ClaimActions.DeleteClaim("nbf"); ClaimActions.DeleteClaim("exp"); ClaimActions.DeleteClaim("at_hash"); ClaimActions.DeleteClaim("c_hash"); ClaimActions.DeleteClaim("auth_time"); ClaimActions.DeleteClaim("ipaddr"); ClaimActions.DeleteClaim("platf"); ClaimActions.DeleteClaim("ver"); // http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims ClaimActions.MapUniqueJsonKey("sub", "sub"); ClaimActions.MapUniqueJsonKey("name", "name"); ClaimActions.MapUniqueJsonKey("given_name", "given_name"); ClaimActions.MapUniqueJsonKey("family_name", "family_name"); ClaimActions.MapUniqueJsonKey("profile", "profile"); ClaimActions.MapUniqueJsonKey("email", "email"); _nonceCookieBuilder = new TrustNonceCookieBuilder(this) { Name = TrustDefaults.CookieNoncePrefix, HttpOnly = true, SameSite = SameSiteMode.None, SecurePolicy = CookieSecurePolicy.SameAsRequest, IsEssential = true, }; }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddDbContext <AppIdentityDbContext>(opts => { opts.UseSqlServer(configuration["ConnectionStrings:DefaultConnectionString"]); }); services.AddIdentity <AppUser, AppRole>(opts => { opts.Password.RequiredLength = 6; opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "abcçdefgðhiýjklmnoöpqrsþtuvwxyzABCÇDEFGÐHIÝJKLMNOÖPQRSÞTUVWXYZ0123456789-._"; opts.Password.RequireDigit = false; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; } ).AddErrorDescriber <CustomIdentityErrorDescriber>().AddUserValidator <CustomUserValidator> ().AddPasswordValidator <CustomPasswordValidator>().AddEntityFrameworkStores <AppIdentityDbContext>().AddDefaultTokenProviders(); CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "MyBlog"; cookieBuilder.HttpOnly = false; cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.LoginPath = new PathString("/Home/Login"); opts.Cookie = cookieBuilder; opts.ExpireTimeSpan = TimeSpan.FromDays(60); }); services.AddMvc(options => options.EnableEndpointRouting = false); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppIdentityDbContext>(opts => { opts.UseSqlServer(configuration["ConnectionStrings:DefaultConnectionString"]); }); CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "AdminBlog"; cookieBuilder.HttpOnly = false; cookieBuilder.Expiration = System.TimeSpan.FromDays(60); cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.LoginPath = new PathString("/Home/Login");// BURAYI UNUTMA ÇÜNKÜ D??ER S?TE ?LE B?RLE??NCE BURAYI KULLANACAKSIN. opts.Cookie = cookieBuilder; opts.SlidingExpiration = true; }); services.AddIdentity <AppUser, AppRole>(opts => { opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "abcçdefgh?ijklmnopqrs?tuüvwxyzABCÇDEFGHI?JKLMNOPQRS?TUÜVWXYZ0123456789-._"; opts.Password.RequiredLength = 4; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; opts.Password.RequireDigit = false; }).AddPasswordValidator <CustomPasswordValidator>() .AddUserValidator <CustomUserValidator>() .AddErrorDescriber <CustomIdentityErrorDescriber>() .AddEntityFrameworkStores <AppIdentityDbContext>(); services.AddMvc(); //uygulamayla ilgili(mvc) tüm servisleri aya?a kald?r?r. services.AddMvc(options => options.EnableEndpointRouting = false); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppIdentityDbContext>(opt => { opt.UseSqlServer(Configuration["ConnectionStrings:DefaultConnectionString"]); }); //cookie yapýsý services.AddIdentity <AppUser, AppRole>(opt => { opt.User.RequireUniqueEmail = true; opt.User.AllowedUserNameCharacters = "abcçdefgðhýijklmnoçpqrsþtuüvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._"; opt.Password.RequiredLength = 4; opt.Password.RequireNonAlphanumeric = false; opt.Password.RequireLowercase = false; opt.Password.RequireUppercase = false; opt.Password.RequireDigit = false; }).AddPasswordValidator <CustomPasswordValidator>().AddUserValidator <CustomUserValidator>().AddErrorDescriber <CustomIdentityErrorDescriber>().AddEntityFrameworkStores <AppIdentityDbContext>(); CookieBuilder cookieBuilder = new CookieBuilder(); cookieBuilder.Name = "MyBlog"; cookieBuilder.HttpOnly = false; cookieBuilder.SameSite = SameSiteMode.Lax; cookieBuilder.SecurePolicy = CookieSecurePolicy.SameAsRequest; services.ConfigureApplicationCookie(opts => { opts.LoginPath = new PathString("/Home/Login"); opts.LogoutPath = new PathString("/Member/LogOut"); opts.Cookie = cookieBuilder; opts.SlidingExpiration = true; opts.ExpireTimeSpan = System.TimeSpan.FromDays(60); opts.AccessDeniedPath = new PathString("/Member/AccessDenied"); }); services.AddMvc(options => options.EnableEndpointRouting = false); }