Kolya_Net
Kolya_Net

Reputation: 1140

How to get in returnUrl AccessDeniedPath in ASP.NET MVC 6 (ASP.NET Core)

I use the latest version of ASP.NET MVC 6.

The following settings are set Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
            services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
            {
                options.Cookies.ApplicationCookie.LoginPath = new PathString("/account/login");
                options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/error/accessdenied");
                options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
                options.Cookies.ApplicationCookie.SlidingExpiration = false;
                options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
                options.Cookies.ApplicationCookie.AutomaticChallenge = true;
            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
}

In the Account Controller has action Login

        [HttpGet]
        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

In the method above I have no problem getting returnUrl.

Also in the controller Error has action AccessDenied

        [AllowAnonymous]
        [HttpGet]
        public IActionResult AccessDenied(string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

But when the user has no permission to access the pages of the site, the system forwards the user to a page ../error/accessdenied.

At the moment, after I get redirected returnUrl value is null.

Can I get the address of the page from which the user was redirected (as well as it works for LoginPath)?

Upvotes: 2

Views: 2541

Answers (1)

Fabien ESCOFFIER
Fabien ESCOFFIER

Reputation: 4911

It seems it will be shipped in the RC2, take a look at the CookieAuthorizationHandler.HandleForbiddenAsync method source code on GitHub,

protected override async Task<bool> HandleForbiddenAsync(ChallengeContext context)
{
    var properties = new AuthenticationProperties(context.Properties);
    var returnUrl = properties.RedirectUri;
    if (string.IsNullOrEmpty(returnUrl))
    {
        returnUrl = OriginalPathBase + Request.Path + Request.QueryString;
    }
    var accessDeniedUri = Options.AccessDeniedPath + QueryString.Create(Options.ReturnUrlParameter, returnUrl);
    var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(accessDeniedUri), properties);
    await Options.Events.RedirectToAccessDenied(redirectContext);
    return true;
}

You can have a feedback on how to migrate from RC1 to RC2 on the Home repository.

Upvotes: 2

Related Questions