.htaccess check for cookie first, then valid-user

2019-08-14 12:15发布

I have a .htaccess file for a directory on my apache server. Currently this makes use of mod_auth_mysql for user verification to view the directory listing. However, if the user is already logged in to my application (therefore a cookie exists), I want to skip the valid user requirement and therefore eliminate multiple logins.

Current .htaccess

AuthName "Please don't hack the server, cheers"
AuthBasicAuthoritative Off
AuthUserFile /dev/null
AuthMySQL On
AuthType Basic
Auth_MYSQL on
Auth_MySQL_Host localhost
Auth_MySQL_User username
Auth_MySQL_Password password
AuthMySQL_DB auth
AuthMySQL_Password_Table users
Auth_MySQL_Username_Field username
Auth_MySQL_Password_Field password
Auth_MySQL_Empty_Passwords Off
Auth_MySQL_Encryption_Types Plaintext
Auth_MySQL_Authoritative On
require user james

The Cookie Check

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !^cookiename=ok$
RewriteRule .* / [NC,L]

How do I combine these two correctly, to first check for the cookie and allow through if found, and then check for a valid user if the cookie is not found?

Thanks

1条回答
Melony?
2楼-- · 2019-08-14 12:24

You need to do 2 things here, you can create an environment variable using the SetEnvIf directive and check it against Cookie. Then you need to tell mod_auth_mysql to allow any set of requirements to satisfy the authentication.

First the environment variable:

SetEnvIf Cookie cookiename=ok norequire_auth=yes

The cookiename=ok is a regular expression that matches against the Cookie: HTTP header. Then the Satisfy:

Order Deny,Allow
Satisfy Any

# your auth stuff:
AuthName "Please don't hack the server, cheers"
AuthBasicAuthoritative Off
AuthUserFile /dev/null
AuthMySQL On
AuthType Basic
Auth_MYSQL on
Auth_MySQL_Host localhost
Auth_MySQL_User username
Auth_MySQL_Password password
AuthMySQL_DB auth
AuthMySQL_Password_Table users
Auth_MySQL_Username_Field username
Auth_MySQL_Password_Field password
Auth_MySQL_Empty_Passwords Off
Auth_MySQL_Encryption_Types Plaintext
Auth_MySQL_Authoritative On
require user james

Allow from env=norequire_auth

So the Satisfy Any means we allow if require user james is satisfied or if Allow from env=norequire_auth is satisfied. Without the satisfy, both lines would need to be satisfied in order to allow access.

Note that cookies can easily be forged and this system isn't a good way to protect your pages. You'd at least need to check the cookie's value for a session ID or something.

查看更多
登录 后发表回答