如何获得[授权]重定向到登录页面的原始URL?

时间:2019-01-30 16:46:51

标签: c# authentication asp.net-core asp.net-core-2.2

在我的配置方法中,我有以下内容

...
app.UseStatusCodePagesWithRedirects("/home/login");
app.UseMvcWithDefaultRoute();

当我用 [Authorize] 装饰方法时,我被重定向到 / home / login 。但是,我也希望将用户发送回原籍,为此,我需要像这样将原点传递到登录页面。

...
string origin = ???
app.UseStatusCodePagesWithRedirects("/home/login?origin=" + origin);
app.UseMvcWithDefaultRoute();

是否可以通过某种方式获取 origin 还是我对 UseStatusCodePagesWithRedirects 的调用不太合适?我应该如何处理?

1 个答案:

答案 0 :(得分:2)

首先,如下所示设置启动类

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        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;
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        //-----
        services.AddAuthentication(
            CookieAuthenticationDefaults.AuthenticationScheme
        ).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = "/Account/Login";
                options.LogoutPath = "/Account/Logout";

                // The ReturnUrlParameter determines the name of the query parameter 
                // which is appended by the handler
                // when during a Challenge. This is also the query string parameter   
                // looked for when a request arrives on the 
                // login path or logout path, in order to return to the original url  
                // after the action is performed.
                options.ReturnUrlParameter=origin;//the default value is returnUrl

            });
        services.AddAuthentication(options =>
        {
            options.DefaultScheme =CookieAuthenticationDefaults.AuthenticationScheme;
        });
        //----
    }

    // 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.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

AccountController

    public IActionResult Login(string origin)
    {
        //save original url
        ViewBag.Origin = origin; 
        return View();
    }

    //get the original url from hide input
    [HttpPost]
    public IActionResult Login(LoginViewModel model)
    {
        //if (login successfull)
        //{
            return Redirect(model.Origin);
        //}
        // else
        //{
            return View(model);
        //}
    }