I am working on a web application made in .NET Core
with Razor Pages.
I'd like to redirect the user if they are not logged in to the login page. If they log in - the system should redirect the user to it's first requested link/original link.
This is my current Configure
-method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
{
...
app.Use(async (ctx, next) =>
{
await next();
if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
//Re-execute the request so the user gets the error page
string originalPath = ctx.Request.Path.Value;
ctx.Items["originalPath"] = originalPath;
ctx.Request.Path = "/error";
await next();
}
});
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
So if a users requests /Dashboard/Settings/Account/Password for example and he is not logged in, I'd like to redirect him to the Login page first, and after he submits he will be redirected to that link instead of /Dashboard.
I am not sure how I can adapt this script ( source )
// In my login
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
if(!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToPage("/Dashboard/Index");
}
I think the problem lies here. My ReturnUrl is null
. So it always redirects to the homepage.
What I did for cookie authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = "/Home/Login/"; // auth redirect
options.ExpireTimeSpan = new TimeSpan(1,0,0,0 );
});
[Authorize] // set authorize will auto redirect to specified LoginPath
public IActionResult yourmethod()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.