views:

99

answers:

4

Does anyone know of a way to get ASP.NET Forms Authentication to not redirect back to the login page if a user is not allowed to visit a certain page or folder based on their role (and perhaps show a message instead)?

A: 

If you don't want it to redirect back to the login page, then what page do you want to resolve, the requested page, which they don't have access to? If so, and if you want that URL to be in their address bar, then you will need to override the base ASP.NET page, and prevent the continuation of rendering, and instead return an simple page with a pop up message or something.

Josh Pearce
A: 

I think you'll have to change the authorization in web.config for the given page's location so that everyone is authorized.

<configuration>
   <location path="somepage.aspx">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

Then you can use Roles.IsUserInRole() in the page logic to determine if they are authorized, and then display a message if they are not. I've done this before when I use the same aspx page for viewing and editing a record where anyone can view but only certain roles can edit.

jrummell
A: 

4GuysFromRolla have a pretty detailed tutorial on how to use the membership provider. The link provided gives you details about how to apply user- and role-based authorization rules to methods and classes.

Hope this helps some.

Chris
+2  A: 

The redirect happens because the user is not authorized to see the page - not because she is not authenticated with the system. As such, the framework does not distinct between the situation where a user is "not logged in" and the situation where she is just "missing the required role". If she does not have acccess, she is redirected to the login page - end of story.

What I usually do, is to create my login form with a MultiView with a view for each of the two cases, as well as one for the case where the user asked for the login form himself. Then I do something like this to toggle between the different views:

if (Request.QueryString["ReturnUrl"] == null)
   myMultiView.ActiveViewIndex = 0;               // user asked for login form
else if (Request.IsAuthenticated)
   myMultiView.ActiveViewIndex = 1;               // insufficient rights
else
   myMultiView.ActiveViewIndex = 2;               // login required

Rather than using a MultiView you could also insert a Response.Redirect in branch above, if this seems to make more sence in your application - e.g. if the three login forms are significantly diverse.

Jørn Schou-Rode