在我的ASP.CORE应用中,我使用了用户身份验证。
我接下来要做的是:如果用户访问该站点,但前提是该站点未获得他的授权-显示他的主页,但是如果该站点之前已被授权,则给他显示另一个页面(在本例中为加密控制器页面)。 但是如果他从主页导航到/ Encrypt,程序应该将他重定向到登录页面(它现在如何工作)。
在“配置”中启动时,如果用户之前获得了用户的授权,则我尝试重定向到另一个页面/ Encrypt(默认),但如果之前没有被授权,则可以进行所有工作(他重定向到/ Encrypt页面),程序会将他重定向到Account Controller上的Login页面。 这就是问题。
我注意到如果用户之前获得过授权(仅当之前未经授权(没有身份验证cookie)时),帐户控制器不会启动,因此我无法使用Account Contoller进行重定向。 那么,在哪里拦截请求(或了解它)或在哪里检查cookie以进行授权?或如何处理?
我的启动设置:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>();
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Encrypt}/{action=Index}");
});
}
我的帐户控制器如下:
public class AccountController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
public AccountController(UserManager<User> userManager, SignInManager<User> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["UserName"] = this.GetUserName();
return View(new LoginViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result =
await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
if (result.Succeeded)
{
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
return View(model);
}
我的加密控制器看起来像:
[Authorize]
public class EncryptController : Controller
{ ... }
答案 0 :(得分:0)
将此代码添加到您的启动中以处理访问请求:
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Account/Access-Denied";
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Signout";
options.SlidingExpiration = true;
});
具体来说,.AccessDeniedPath
可以将其附加到“加密”视图中来缓解您的问题...
答案 1 :(得分:0)
我找到了部分解决方案。
进行如下配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
}
像这样的家庭控制器:
public IActionResult Index()
{
if (User.Identity.IsAuthenticated & !HttpContext.Session.Keys.Contains("Key"))
{
HttpContext.Session.SetInt32("Key", 1);
return RedirectToAction("Index", "Encrypt");
}
else
return View();
}
但是它在会话期间只能工作1次,因此要第二次工作,需要通过关闭浏览器重新开始会话。
所以还是不好。
如果我将始终只在获得授权的情况下从主页重定向-他将永远不会看到主页。太不好了。