Unauthorized request does not redirect to login page with returnUrl query string parameter

醉酒当歌 提交于 2019-12-11 05:59:38

问题


Setup

In my MVC3 app, MembersController is decorated with an [Authorize] attribute.

MembersController has an Action called MyPage. Due to the Authorize attribute on the controller, MyPage can only be requested by authorized users.

Problem

When an unauthorized user tries to request /Members/MyPage they are correctly redirected to the Login page.

However, the ReturnUrl parameter is not passed into the login page, so when the user authenticates, they are taken to the default page (lets call it /Members/Home) instead of /Members/MyPage.

Question

Why?!

In another app, developed in MVC2, the returnUrl QS parameters is there and works as expected.

Other Issues:

The Autorize attribute is being ignored when decorating both controllers and actions.

Resolution:

Sections of web.config not properly updated between .NET 3.5 and .NET 4. See answers below.


回答1:


@Marcind put me on the right track, @Darin Dimitrov's answer very instructive of the process involved.

Diagnosis

It seems that the issue was related to a web.config that I did not update properly when merging an existing Web Forms .NET 3.5 app to a .NET 4.0 app. I can't recall how I went about this.

Anyway, by comparing the web.config of my app with a new MVC 3 web.config, I was able to find the extra bits that should not have been there, left over from 3.5 days.

Resolution:

The issue was resolved by correcting the bits in the <authentication><forms> tag in the web.config, as well as the <membership> tag.

Other Issues Caused by this:

Another issue caused by this was the fact that if I decorated a controller with the Authorize attribute, it was ignored, so the controller tried to process info based on the current user, that obviously was null, so all manner of exceptions were fired.




回答2:


It works for me. I created a new project using the ASP.NET MVC 3 RC2, default template, added a MembersController, decorated it with the [Authorize] attribute, run the application, requested /members/index, was redirected to /Account/LogOn?ReturnUrl=%2fmembers%2findex, logged in, was redirected to /members/index. There must be something else wrong with your code.

Here's how it works:

  • The [Authorize] attribute checks if the user is authenticated and if it is not it returns 401 status code.
  • The FormsAuthenticationModule which is part of ASP.NET and handles forms authentication intercepts the 401 status code and redirects to the login page by appending the ReturnUrl parameter to the request which points to the initial request.

The FormsAuthenticationModule module is not specific to ASP.NET MVC, this is standard ASP.NET stuff



来源:https://stackoverflow.com/questions/4478570/unauthorized-request-does-not-redirect-to-login-page-with-returnurl-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!