I have a ASP.NET 4.0 website which contains a sub-folder with multimedia files like JPG, PNG, MP4, MP3, etc.
Currently, any user with the full link to the files is able to access the multimedia files without any restriction. I want to find the currently logged in user who is making the request and after checking their permissions from DB allow/disallow them to access the file requested.
I have tried implementing a Custom HttpModule
for this purpose but I am not able to find the current user making the request. Below is my code:
public class CustomHttpModule : IHttpModule
{
private const string URL_TO_LOOK_FOR = "/MultiMediaFiles/";
public CustomHttpModule()
{ }
public void Init(HttpApplication app)
{
app.AuthenticateRequest += CustomAuthenticateRequest;
//app.EndRequest += CustomAuthenticateRequest;
}
void CustomAuthenticateRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
Uri url = context.Request.Url;
if (url.AbsolutePath.StartsWith(URL_TO_LOOK_FOR, StringComparison.OrdinalIgnoreCase))
{
var response = context.Response;
response.Clear();
response.Write("app.Context.User :");
if (context.User == null || context.User.Identity == null || context.User.Identity.Name == null)
{
response.Write("No user");
}
else
{
response.Write(context.User.Identity.Name);
}
response.End();
response.Flush();
response.Close();
}
}
public void Dispose()
{ }
}
I tried attaching to events: BeginRequest
, AuthenticateRequest
, PostAuthenticateRequest
and even EndRequest
, but in each case context.User
is always null
even after I have logged in to my website.
EDIT:
I am using the FormsAuthentication
and my web.config contains:
<system.web>
<authentication mode="Forms">
<forms name="MyWebFORMAUTH" timeout="60"
loginUrl="~/web/logon/default.aspx" cookieless="UseCookies"
defaultUrl="~/web/logon/default.aspx"
slidingExpiration="true" />
</authentication>
</system.web>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="CustomHttpModule"/>
</modules>
<system.webServer>
NOTE: I cannot modify the links to multimedia files.
Please HELP.