views:

1158

answers:

2

Hi. Now I'm trying to work with System.Web.Routing. All is just fine, but I can't understand how to make form authentication work with url routing (return url, redirection, etc). Google says nothing. Help! :)

UPD: I forgot - I don't use MVC. That's the problem. How to use rounig and form authentication without MVC

UPD2: more about my problem
What I want to get: urls such “mysite.com/content/123”, “mysite.com/login/”, etc using Routes. It’s important to make login page works like “regular” ASP.NET login form (redirects to login from secure area when not login on, and redirect back to secure area when loggined).
That’s what I’m doing.
In global.asax on Application_Start, register routes like this:

routes.Add("LoginPageRoute", new Route("login/", new CustomRouteHandler("~/login.aspx")));
routes.Add("ContentRoute", new Route("content/{id}", new ContentRoute("~/content.aspx"))
      {
       Constraints = new RouteValueDictionary {{ "id", @"\d+" }}
      });

Where CustomRouteHandler and ContentRoute – simple IRouteHandler classes, just like:

…
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
…

All seems to be perfect: I’m getting content.aspx when go to “/content/10” and login.aspx when go to “/login/”. But…
When I make content secured (in web.config, with deny=”?”), login form doesn’t work like expected.
Now I can’t reach the “/content/10” page:

0. I’m typing “/content/10” in my browser.
1. Site redirects to “/login/?ReturnUrl=%2fcontent%2f10”. (Hm… seems like all problems starts here, right? :)
2. I’m trying to log in. No matter what credentials I’m entered…
3. …site redirects me to “login?ReturnUrl=%2fContent%2f10” (yellow screen of error - Access is denied. Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.)
So, the problem is how to get ASP.NET understand real ReturnUrl and provide redirection after login.

A: 

The first result I got from a Google search is Frederiks excellent post on forms authentication in ASP.NET MVC. Note that the post was relevant for an early version of ASP.NET MVC, you will have to write and test the code.

HTH, Indy

indyfromoz
I updated topic - I don't use MVC. Anyway, thanks for you answer.
lak-b
Sorry, I didn't really help! Maybe if you can give some more details as to what you are trying to achieve will help? Like - + Login.aspx - Login the user with membership API, redirect to secure area. + Secure area (Accessible by logged in users)Something like this?
indyfromoz
topic updated with more details about problem
lak-b
+6  A: 

These steps should allow you to implement the required behaviour.
To summarize:

  1. You are using routing but not MVC. My example will map a url like http://host/Mysite/userid/12345 onto a real page at http://host/Mysite/Pages/users.aspx?userid=12345.
  2. You want to control access to these addresses, requiring the user to logon. My example has a page http://host/Mysite/login.aspx with a standard login control, and the site is configured to use forms authentication.

Step 1

I've "hidden" the contents of the Pages folder using this web.config in the Pages folder:

  <?xml version="1.0"?>
  <configuration>
    <system.web>
      <httpHandlers>
        <add path="*" verb="*"
            type="System.Web.HttpNotFoundHandler"/>
      </httpHandlers>
      <pages validateRequest="false">
      </pages>
    </system.web>
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
      </handlers>
    </system.webServer>
  </configuration>

This ensures that if anyone uses a url like http://host/Mysite/Pages/users.aspx?userid=12345, then they receive a standard 404 response.

Step 2

My top level web.config file contains (as well as all the standard stuff) this location element:

  <location path="userid">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

This prevents anonymous access to urls of the form http://host/Mysite/userid/12345 which means users will be automatically redirected to login.aspx, then if they provide valid credentials, they will be redirected to the correct location.

Step 3

For reference here is my global.asax:

<script RunAt="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
     }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.RouteExistingFiles = true;
        routes.Add("UseridRoute", new Route
        (
           "userid/{userid}",
           new CustomRouteHandler("~/Pages/users.aspx")
        ));
    }

</script>

And here is my route handler:

using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Web.Routing;
using System.Security;
using System.Web.Security;


public interface IRoutablePage
{
    RequestContext RequestContext { set; }
}

public class CustomRouteHandler : IRouteHandler
{
    public CustomRouteHandler(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; private set; }

    public IHttpHandler GetHttpHandler(RequestContext
          requestContext)
    {
        var page = BuildManager.CreateInstanceFromVirtualPath
             (VirtualPath, typeof(Page)) as IHttpHandler;

        if (page != null)
        {
            var routablePage = page as IRoutablePage;

            if (routablePage != null) routablePage.RequestContext = requestContext;
        }

        return page;
    }
}
Dominic Betts
What a fantastic answer!
Atømix