首页 > 解决方案 > 如何获取 [Authorize] 重定向到登录页面的原始 URL?

问题描述

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

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

当我用[Authorize]装饰一个方法时,我被重定向到/home/login。但是,我还希望将用户送回他们来自的地方,为了做到这一点,我需要像这样将来源传递给登录页面。

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

是否有可能以某种方式获得来源,或者我对UseStatusCodePagesWithRedirects的调用不适合?我应该如何处理它?

标签: c#authenticationasp.net-coreasp.net-core-2.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?}");
        });
    }
}

帐户控制器

    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);
        //}
    }

推荐阅读