【发布时间】:2020-03-11 17:33:42
【问题描述】:
我需要使会话过期,当用户尝试重用应用程序时将其送回登录页面。
为此,我修改了 startup.cs 并创建了一个自定义操作过滤器来处理会话过期,如果会话为空,它会重定向到登录操作。
startup.cs 代码
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
string con = Configuration.GetConnectionString("EBBDatabase");
services.AddDbContext<ebbxdbContext>(options => options.UseSqlServer(con));
string con1 = Configuration.GetConnectionString("EBBDatabase");
services.AddDbContext<TelemetryWebContext>(options => options.UseSqlServer(con));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//Session
services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession(options =>
{
options.Cookie.Name = ".Project.Session";
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(3);
options.Cookie.HttpOnly = true;
});
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//identity
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ebbxdbContext>()
.AddDefaultTokenProviders();
services.Configure<SecurityStampValidatorOptions>(options =>
{
options.ValidationInterval = TimeSpan.FromMinutes(3);
});
services.AddMvc(config =>
{
// using Microsoft.AspNetCore.Mvc.Authorization;
// using Microsoft.AspNetCore.Authorization;
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthorization(options =>
{
options.AddPolicy("AllowingDevices", policy =>
policy.Requirements.Add(new EBBDeviceRequirement(true)));
});
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Security/Error.html";
});
//custom classes
services.AddHttpContextAccessor();
services.AddTransient<ICookieService, CookieService>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<IEncryption, Encryption>();
services.AddTransient<INationsService, NationsService>();
services.AddTransient<IDistrictsService, DistrictsService>();
services.AddTransient<IProvincesService, ProvincesService>();
services.AddTransient<ICityService, CityService>();
services.AddTransient<IDeviceService, DeviceService>();
services.AddTransient<IAddressService, AddressService>();
services.AddTransient<ICustomerService, CustomerService>();
services.AddTransient<IWebHelper, WebHelper>();
services.AddTransient<IActivityLogService, ActivityLogService>();
services.AddScoped<IAuthorizationHandler, EBBDeviceHandler>();
AppSettings.AuthKey = Configuration.GetConnectionString("authKey");
AppSettings.Collection = Configuration.GetConnectionString("collection");
AppSettings.Collection2 = Configuration.GetConnectionString("collection2");
AppSettings.Database = Configuration.GetConnectionString("database");
AppSettings.Endpoint = Configuration.GetConnectionString("endpoint");
AppSettings.SpName = Configuration.GetConnectionString("spName");
AppSettings.SpNameDettaglio = Configuration.GetConnectionString("spNameDettaglio");
AppSettings.KeyIoT = Configuration.GetConnectionString("KeyIoT");
AppSettings.urlApi = Configuration.GetConnectionString("UrlApi");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "alias_route_home",
template: "Telemetries/Index",
defaults: new { controller = "Telemetries", action = "Pagina2" });
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "alias_route_home_1",
template: "Telemetries",
defaults: new { controller = "Telemetries", action = "Pagina2" });
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "alias_route_events",
template: "Events/Index",
defaults: new { controller = "Events", action = "Pagina5" });
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "alias_route_events_1",
template: "Events",
defaults: new { controller = "Events", action = "Pagina5" });
});
}
属性自定义代码
public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = filterContext.HttpContext;
if (!ctx.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/Account/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
在这种情况下,过期状态似乎不会出现。 我做错了什么?
【问题讨论】:
-
我不熟悉 ASP.NET Core,但是在经典的 ASP.NET 中,您会使用身份验证并使其在一定时间后过期。然后你不需要强制用户回到登录页面; ASP.NET 为您做这件事。我假设你可以在 ASP.NET Core 中做同样的事情。您不需要重新发明轮子。
标签: c# session asp.net-core asp.net-identity