Authenticated Upload

Authenticated Upload

Require authentication before allowing file uploads. Configure Forms Authentication in web.config so only logged-in users can access the upload page and handler.

Drag & drop files here, or paste from clipboard
<%-- web.config: Forms Authentication configuration --%>
<system.web>
    <authentication mode="Forms">
        <forms loginUrl="~/Login.aspx" timeout="30" />
    </authentication>
    <authorization>
        <deny users="?" />
    </authorization>
</system.web>

<%-- Protect the upload handler specifically --%>
<location path="upload.ashx">
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</location>

<%-- Code-behind: check authentication in upload handler --%>
public class UploadHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            context.Response.StatusCode = 401;
            context.Response.Write("Authentication required.");
            return;
        }

        string userId = context.User.Identity.Name;
        // Save file associated with the authenticated user
        HttpPostedFile file = context.Request.Files[0];
        file.SaveAs(Path.Combine(uploadDir, file.FileName));
    }
}