Using PHP/Apache to Restrict Access to Static Files (Html, CSS, Img, etc)

Using PHP/Apache to restrict access to static files (html, css, img, etc)

I would consider using a PHP loader to handle authentication and then return the files you need. For example instead of doing <img src='picture.jpg' /> Do something like <img src='load_image.php?image=picture.jpg' />.

Your image loader can verify sessions, check credentials, etc. and then decide whether or not to return the requested file to the browser. This will allow you to store all of your secure files outside of the web accessible root so nobody is going to just WGET them or browse there 'accidentally'.

Just remember to return the right headers in PHP and do something like readfile() in php and that will return the file contents to the browser.

I have used this very setup on several large scale secure website and it works like a charm.

Edit: The system I am currently building uses this method to load Javascript, Images, and Video but CSS we aren't very worried with securing.

How to prevent user to access css files and images via the url

Please following rules at the top of your htaccess rules file. You need not to create 3 separate rules for 3 conditions, you can use regex here and can do a 401 redirect for all of 3 strings(js/images/css) in a single rule itself.

Make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
RewriteRule ^frontend/assets/(?:images|css|js) - [R=401,NC,L]

How can I restrict the access to a static file to a specific logged in user?

You could use a Middleware + Authorization Policy to achieve that goal:

  1. Define a policy where the user can only access his own resources.
  2. Invoke the IAuthorizationService within a middleware that checks the policy before it goes into the StaticFiles middleware.

For example, here's a AuthorizationHandler that handles this requirement:

public class RestrictStaticFilesRequirement: AuthorizationHandler<RestrictStaticFilesRequirement>,IAuthorizationRequirement 
{
public const string DefaultPolicyName = "Access-His-Own-Static-Files";
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RestrictStaticFilesRequirement requirement)
{
var user = context.User; // current User Principal
var userName = context.Resource as string; // current userName
// custom this requirement as you like
if(user != null && !string.IsNullOrEmpty(userName) && user.HasClaim(ClaimTypes.NameIdentifier, userName)) {
context.Succeed(requirement);
} else {
context.Fail();
}
return Task.CompletedTask;
}
}

Register this requirement as a Policy:

services.AddAuthorization(opts =>{
opts.AddPolicy(RestrictStaticFilesRequirement.DefaultPolicyName,pb => pb.AddRequirements(new RestrictStaticFilesRequirement()) );
});

Finally, check the policy using the IAuthorizationService and determine whether current request is allowed:

app.UseAuthentication();

app.UseWhen( ctx => ctx.Request.Path.StartsWithSegments("/files/users"), appBuilder =>{
appBuilder.Use(async (context, next) => {
// get the userId in current Path : "/files/users/{userId}/...."
var userId = context.Request.Path.Value.Substring("/files/users/".Length)
.Split('/')
.FirstOrDefault();
if(string.IsNullOrEmpty(userId)){
await next(); // current URL is not for static files
return;
}
var auth= context.RequestServices.GetRequiredService<IAuthorizationService>();
var result = await auth.AuthorizeAsync( context.User, userId ,RestrictStaticFilesRequirement.DefaultPolicyName);
if(!result.Succeeded){
context.Response.StatusCode= 403;
return;
}
await next();
});
});
app.UseStaticFiles();

// ... other middlewares

How to restrict access to certain kind of content, with apache or .htaccess?

Keep all the images in their own directory, and in that directory, put a .htaccess file with this in it

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !^.*name-of-my-cookie.*$ [NC]
RewriteRule .* /whatever/page [NC,L]


Related Topics



Leave a reply



Submit