Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm making a website and there is a page on said website which I would like only certain people to access, with a password. I was wondering the best way to go about it simply and securely, and would love some example code if any exists.
To clarify, I would like to add a feature to a page on my website which prevents anyone visiting the site from going to that page unless they enter a password. I'm mostly looking for HTML, JS, or JQuery solutions, as this is only going to be for the users of the website.
The simplest way that I've come across is using an htpasswd file (which looks very similar to /etc/passwd if you are familiar with that), then setting up your webserver to point at it.
# create htpasswd file
htpasswd -c /path/htpasswd
# add user to htpasswd file (you'll be prompted for password)
htpasswd /path/htpasswd loginuser
Within your nginx.conf , set it up like this
server {
listen 80 yourserver;
listen [::]80 yourserver ipv6only=on;
root /var/www/yourserver;
index index.html;
location /public {
# ...
}
# everything under /private requires a login
location /private {
auth_basic "Restricted Content";
auth_basic_user_file /path/htpasswd;
}
}
There's a really good tutorial on this setup, that I shamelessly robbed for this answer here:
https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04
Then for anything over/above that, nginx's documentation is excellent as well (if that is the webserver you are using).
https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
One trap with this setup is that nginx only allows password hashes that are supported by your operating system's crypt module. So linux for example wouldn't necessarily have bcrypt, but most of the BSDs would. You can find what your OS's crypt module supports using man crypt .
|
If you're looking for something where you have a little more control, you can have a URL that you GET a website with form data, which POSTs the login information to a URL you can handle the login details yourself. This is python/flask - I'm not sure it is what you are looking for bsaed on your tags but it may still be helpful.
https://pythonspot.com/login-authentication-with-flask/
I hope this was helpful :) good luck!
Depending on what frameworks, applications etc. you are using to create your website, and If you want create an account system or just a protected area, there are many different ways.
1. .htaccess:
Assuming you are using a NCSA-compatible webserver such as apache and want to restrict access to a certain path, the simplest (yet by far not safest) way to do that would be to use a simple .htaccess-file.
simply put a file with that exact name into the folder you want to protect with following content:
AuthType Basic
AuthName "Enter Credentials Here"
AuthUserFile /full/path/to/.htpasswd
Require valid-user
and create a .htpasswd file in a safe place containing
username:password
or, if you care about people hacking your server getting the password:
username:hash
you can generate hashes using online-.htpasswd-generators.
Make sure to enter the path to your .htpasswd correctly into your .htaccess!
The .htaccess file will make the server ask for basic username/password authentication, show the message "Enter Credentials Here" to the user and require the users browser to send any valid credentials to your server. Valid credentials mean any username/password-pair in your .htpasswd file. Just know that the user's browser will always send the credentials to your server unencrypted, so make sure to enable https, if you care about the password not being stolen from your users. And tell them not to write it down etc. basic password safety.
2. Fancy Account System using SQL
This is more complicated an probably not what you want, so I will just give basic advice: Read about sql injection and make sure you fully understand it and how to avoid it. Read about password hashing and salting. Read about safe passwords (phrases) to advice your users. Read about html forms and how to parse them using your framework. Read about encryption. Then create a concept that fits your needs and implement it.
If you are using PHP then this is simple solution:
<?php
if(!isset($_POST["password"])){
header("location:pwdnotcorrect.php");
return;
}
$pwd=$_POST["password"];
if($pwd!="yourpassword"){
header("location:pwdnotcorrect.php");
return;
}?>
<!--Your HTML Code starts here--->
Send POST request with password to this page using form
If password not correct then this page redirect you to new page.
Related
I'm having an issue getting Login Kit to work. Similar to the question asked here I have the correct redirect domain listed in tiktok settings and the redirect_uri is basically just "domain/tiktok" but no matter what I do I get the same error message:
Below is my backend code - it's basically exactly the same as what is listed in the tiktok docs. Any help on this would be much appreciated!
const CLIENT_KEY = 'my_key'
const DOMAIN = 'dev.mydomain.com'
const csrfState = Math.random().toString(36).substring(2);
res.cookie('csrfState', csrfState, { maxAge: 60000 });
const redirect = encodeURIComponent(`https://${DOMAIN}/tiktok`)
let url = 'https://www.tiktok.com/auth/authorize/';
url += '?client_key=' + CLIENT_KEY;
url += '&scope=user.info.basic,video.list';
url += '&response_type=code';
url += '&redirect_uri=' + redirect;
url += '&state=' + csrfState;
res.redirect(url);
UPDATE 8/13/2022
I submitted the app for review and was approved so the status is now "Live in production" instead of "staging". The issue is still there - still showing error message no matter what domain / callback URL I use
UPDATE 8/16/2022
OK so I've made some progress on this.
First off - I was able to get the authentication/login screen to finally show up. I realized to do this you need to:
Make sure that the status of your app is "Live in production" and not "Staging". Even though when you create a new app you may see client_key and client_secret show up don't let that fool you - Login Kit WILL NOT WORK unless your app is submitted and approved
The redirect_uri you include in your server flow must match EXACTLY to whatever value you entered in "Registered domains" in the Settings page. So if you entered "dev.mydomain.com" in Settings then redirect_uri can only be "dev.mydomain.com" not "dev.mydomain.com/tiktok".
I think I might know what the issue is. My guess is that before - on the Settings page you had to enter the FULL redirect URL (not just the domain) and whatever redirect uri was included in the authorization query was checked against this value which was saved in TikTok's database (whatever was entered in the Settings page when path/protocol were allowed). At some point recently, the front-end business logic was changed such that you could only enter a domain (e.g., mydomain.com) on the Settings page without any protocols - however TikTok's backend logic was never updated so during the Login flow they are still checking against an EXACT match for whatever was saved in their DB as the redirect uri - this would explain why an app that was previously using the API with a redirect uri that DOES include protocols (e.g., for Later.com their redirect uri is https://app.later.com/users/auth/tiktok/callback) continues to work and why for any app attempting to save redirect WITH protocols are getting the error message screen. My gut feeling is telling me that the error is not on my part and this is actually a bug on TikTok's API - my guess is it can be addressed either by changing the front-end on the Settings page to allow for path/protocols (I think this is the ideal approach) or to change their backend so that any redirect uri is checked such that it must include 1 of the listed redirect domains.
I've been emailing with the TikTok team - their email is tiktokplatform#tiktok.com - and proposed the two solutions I mentioned above. I suggest if you're having the same issue you email them as well and maybe even link this StackOverflow question so that maybe it will get higher priority if enough people message them about it.
If you're looking for a shot-term hack I'd recommend creating a dedicated app on AWS or Heroku with a clean domain (e.g., https://mydomain-tiktok.herokuapp.com) and then redirect to either your dev or production environment by appending a prefix to the "state" query (e.g., "dev_[STATE_ID]"). I'll just reiterate I consider this a very "hacky" approach handling callbacks and would definitely not want to use something like this in production.
In my case, the integration worked after doing following steps:
In TikTok developers page:
Like #eugene-blinn said: make sure your app is in Live in production status (I couldn't find anything in the documentation about why Staging apps don't work);
Add the Login Kit product to your app and set the Redirect domain field with your host domain, for example: mywebsite.com.
In your code:
From my tests, I could add whanever url path I wanted, the only constraint was that the domain should match with step 2. So, yes, you can add https://mywebsite.com/whatever/path/you/want in redirect_url parameter.
That's it. It should work with these 3 steps.
Additionally, I got other issue related to use specific features in the scope property (like upload or read videos, etc), so here the solution as well:
Only add Video Kit product to the TikTok app and set video.upload or video.list in the scope authorize request won't work unless you also add the TikTok API product in your TikTok app as well. Btw, it neeeds to be approved too.
TikTok fixed the bug that resulted in URL mismatch with redirect domain from working. However, they fixed it only for paths (e.g., /auth/tiktok) but PORT additions still result in an error - so www.domain.com:8080/auth/tiktok won't work but www.domain.com/auth/tiktok WILL work
UPDATE 10/3/2022
Got the following response directly from TikTok engineering team:
At this point, we only support production integrations with TikTok for Developers and require that you have a URL without port number. However, we understand from your communication that this makes it harder for you to build, test, and iterate your integration with us. Unfortunately, at this time, we do not have a timeline for when this additional support for development servers will be added. We request that you only redirect to URLs without port numbers. Thank you for the feedback.
The frontend of the developer's dashboard still rejects protocol and path in validation. However, the backend skips the path validation.
To be able to update the "Redirect domain" simply:
Open dev tools in chrome and go to the "Network" tab.
Clic on "Save changes" button on the dashboard.
Right clic on the "publish" request that appeared and copy as cURL.
Modify the "redirect_domains" field in the request before pasting it in the terminal.
I believe the app still needs to be approved and in production to get it to work. I'm still waiting for approval and it has been a couple of weeks.
UPDATE 9/17/2022
Just like #mauricio-ribeiro, my app worked after it was approved to production. Setting up the redirect domain without path and scheme works just fine.
I had the same problem, my solution:
1.- In my TikTok App dashboard, the “redirect_uri” is: mydomain.com, without http/https and without path (/my-redirect-url). Also you can add subdomains using this rule
2.- In my code, I have to add http or https to the redirect_uri, and feel free to use path (/my-redirect-uri)
I hope this help you
I need to send only special Users an Email. That is not a big amount. The Website must send 6 E-Mails a week. I found many solutions. I found this simple solution: https://medium.com/#edigleyssonsilva/cloud-functions-for-firebase-sending-e-mail-1f2631d1022e
When you look at the code, I need to fill out the variables. So I must type in my Email and the Password. As the web is opensource I think that is a very bad way. Do you know other simple solutions or know how to do this without typing in password?
With this solution you are using firebase functions. You most certainly want to set some environmental variables to protect some sensitives data like your gmail password.
You can do this in firebase: go check their documentation right here : https://firebase.google.com/docs/functions/config-env
The doc is going to help you set something like :
{
"mailer": {
"mail":"YOUR GMAIL ADRESS",
"password":"YOUR GMAIL PASSWORD"
}
}
So instead of you password in plain text you'll have this in your code :
'password': `${functions.config().mailer.password}`
Much safer right ?
The web is not open source. If you run a script in the browser then yes, the user can read the code. The example you link, however, runs on the server in response to HTTP(S) requests, and as such is not readable by a visitor.
How can I make an HTML (and CSS/PHP/JavaScript) document which only allows certain IP addresses on a page?
(I am not asking how to find IP address with PHP, but how to allow access to a page based on an IP address.)
put this on the top of your php file and update the allowedIps variable with the IPs that you want to allow.
$allowedIps = ['198.x.x.x', '200.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
for non PHP files (eg .html, .css) you will have to update your .htaccess file to add file specific permission. The following SOF thread should help: (assuming you are using apache server)
.htaccess: how to restrict access to a single file by IP?
If you dont want to bother with the code, put your site on Cloudflare and block ips
Try this with PHP :
function CheckIPAccess() {
//allowed IP. Change it to the IP addresses you want to allow to access your webpage
$allowedip = '127.0.0.1';
$ip = $_SERVER['REMOTE_ADDR'];
return ($ip == $allowedip);
}
Usually, IP restrictions are done at the web-server configuration level, so that unauthorized IPs simply can't reach your code at all.
It would actually be quite messy to try to do this kind of check within your application – "you'd undoubtedly miss one" – but the server can easily do it for you.
(I do not recommend attempting to use IPs for privilege checking and so forth ... "IPs change. Frequently. Very messy. Very ...")
Even stronger yet would be firewalls, and maybe VPNs. You really want to keep intruders as far away as possible and to give them as little information as possible. (For instance, why should they even be able to detect that the web-server exists?) Strive to make the entire setup as "hardened" as possible.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For a huge project, we're going to make a "superadmin" login (all other admin work is directly in frontend) for a place where you can alter a lot of things.
As security is really really important, I've been thinking about only allow people with a certain IP to connect. Does anyone knows of websites that do the same, is it overly protective or can you recommend another really secure way of doing admin-work?
We can make it for a specific browser-only if theres some useful possibilities in Chrome or Firefox.
FYI the frontend is javascript, html and css only
It can be good protection, if you can be assured that all "superadmins" will have static IP address, and will not be unable to use application because their IP changed in the middle of the night.
Other method, similar to the one you mentioned, is VPN, where users after connecting to VPN would have an IP address from your private pool, and your application would accept connections only from that pool (even better, you can make apache/nginx vhost for the superadmin application listen only on VPN ip).
Another positive side of the VPN approoach, is that you are securing the traffic too, apart from filtering access.
It won't make sense to do it client-side, since there isn't really anything stopping an attacker from modifying/disabling your JS.
So only secure option is server-side. I've done so myself with a CMS system in PHP.
UPDATE: Sample Implementation
In that project, I used a GeoIP-service (like this one from MaxMind)
function geoIPRequest($ip){
$params = getopt('l:i:');
if (!isset($params['l'])) $params['l'] = '<userIDtoMaxMind>';
if (!isset($params['i'])) $params['i'] = $ip;
$query = 'https://geoip.maxmind.com/a?' . http_build_query($params);
$curl = curl_init();
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $query,
CURLOPT_USERAGENT => 'MaxMind PHP',
CURLOPT_RETURNTRANSFER => true
)
);
$countryCode = curl_exec($curl);
if (curl_errno($curl)) {
throw new Exception(
'GeoIP request failed with a curl_errno of '
. curl_errno($curl)
);
}
return $countryCode;
}
$countryCode = geoIPRequest($_SERVER['REMOTE_ADDR']);
if(!in_array($countryCode, array('DE', 'DK', 'EU', 'GB', 'SE'))){
header('HTTP/1.0 403 Forbidden');
echo "You don't have access";
exit();
}
The code above is adapted from the sample code on MaxMind's website
You'd of course need to adapt it to your use-case. For me specific countries were good enough. If you need to whitelist specific IPs, I'd advised you to create a database table with whitelisted IPs that you then query when someone requests your admin-page.
i have to say, this doesn't sound like a awesome idea
any real security traditionally requires a server component, would recommend the following :
a) make all login pages served over https
b) include a server tech such as ruby/php to do the following:
digest authentication ->
http://en.wikipedia.org/wiki/Digest_access_authentication
which is basically
login details stored in a db (make sure you only store password hashes + salt in db!!!)
php/ruby compared login details to db log in details
once authenticated store this authenticate state as a digest cookie
see here for php implementation : http://www.php.net/manual/en/features.http-auth.php
but seriously please please don't use client implemented security, it's a bad bad idea
for more security concerns and ideas to watch out for see here ->
http://w3af.org/
http://w3af.org/understanding-html5-security
also very good resource for learning about how amazingly evil and good hackers are, and how to thwart their plans
http://www.lulu.com/spotlight/owasp good books on common security flaws (may be free pdfs online)
Lets say I have a php generated javasrcipt file that has the user's name, id number and email adress that is currently logged in. Would a simply document.location.href look up prevent remotes sites from determining the currently logged in user?
Would this be safe?
if(window.document.location.hostname == 'domain.com')
var user = {
name:'me',
id:234243,
email:'email#email.com'
};
else alert('Sorry you may not request this info cross sites.');
Initially it appears safe to me.
EDIT: I had initially thought this was obvious but I am using cookies to determine the currently logged in user. I am just trying to prevent cross domain access to the users info. For example if the if statement was removed malicious site A could embed the javascript file and access the users info. By adding the if statement the user js object should never appear. Cross site ajax isn't supported therefore only through javascript insertion could the malicious site attempt to determine the currently logged in user.
EDIT 2: Would checking my http_refer using php be safe? What if caching is also enabled for the client? For example if the user visits my site A where the user script is downloaded and then later visits site B malicious site would the script be cached, therefore bypassing the need for the server to check the user's http_refer?
You're basically saying "here's the keys to the bank vault, here's the guard's schedule, and here's the staff schedule. But hey, if you're not from the Acme Security Company, pretend I didn't give this to you".
"oh, sure, no problem, lemme just pretend to shred this note and go rent a large truck haul away your vault contents with"
You really just don't want to try something like this. Suppose I'm running an evil site; what do I do?
<script>
RegExp.prototype.test = function() { return true; };
</script>
<script src="http://yoursite.example.com/dynamicjs.php"></script>
<script>
alert("Look at the data I stole: " + user);
</script>
No, what you have there is not "safe" in that it will reveal those details to anyone requesting the HTML page containing that JavaScript. All they have to do is look at the text (including script) returned by the server.
What it comes down to is this: Either you have authenticated the other end to your satisfaction, in which case you don't need the check in the JavaScript, or you haven't, in which case you don't want to output the details to the response at all. There's no purpose whatsoever to that client-side if statement. Try this: http://jsbin.com/aboze5 It'll say you can't request the data; then do a View Source, and note that you can see the data.
Instead, you need to check the origin of the request server-side and not output those details in the script at all if the origin of the request is not authenticated.
Update 1: Below you said:
I was specifically trying to determine if document.location.href could be falsified.
Yes, document.location can be falsified through shadowing the document symbol (although you might be able to detect that if you tried hard enough):
(function() {
var document; // Shadow the symbol
document = {
location: {
href: "http://example.com/foo.html"
}
};
alert("document.location.href = " + document.location.href);
})();
Live copy
Cross-domain checks must happen within the browser's internals, nothing at the level of your JavaScript code can do it securely and robustly.
But that really doesn't matter. Even if it couldn't be falsified, the quoted example code doesn't protect the data. By the time the client-side check is done, the data has already been sent to the client.
Update 2: You've added a note about checking the HTTP_REFERER (sic) header (yes, it really is misspelled). Sadly, no, you can't trust that. HTTP_REFERER can be spoofed, and separately it can be suppressed.
Off-topic: You're probably already doing this, but: When transferring personal details you've promised to keep confidential (I don't know whether you have, but hopefully so), use HTTPS (e.g., SSL). But it's important to remember that while HTTPS ensures that data cannot be read in transit, it does nothing to ensure that the origin of the request is authenticated. E.g., you know the conversation is secure (within reason and current practice), but you don't necessarily know who you're talking to. There's where authentication comes into it.