Check in JavaScript if an SSL Certificate is valid
Solution 1
The question doesn't make sense. You can't get the server's SSL certificate without opening an SSL connection to it, and once you've done that, telling the user they can do that too is a bit pointless.
Solution 2
Take a look here: https://support.mozilla.org/pl/questions/923494
<img src="https://the_site/the_image" onerror="redirectToCertPage()">
However, this may be Mozilla-specific.
Anyway, I would see if a solution along these lines would work:
<script> var sslCertTrusted = false; </script>
<script src="https://example.com/ssltest.js"></script>
<script>
if (!sslCertTrusted)
{
alert('Sorry, you need to install the certificate first.');
window.location('http://example.com/cert_install_instructions/');
}
else
{
// alert('Redirecting to secure connection')
window.location('https://example.com/');
}
<script>
You of course need to make your web server return this code under the URL https://example.com/ssltest.js
:
sslCertTrusted = true;
I'm not exactly sure about the details. But I've seen similar technology used to detect adblocking etc. You may need to piggyback on the window
object maybe, if the variable can't be modified by another script, but generally making the above proof of concept work is left as an exercise to the reader.
Solution 3
What I've found up to now - it is possible with Firefox, don't know yet about other browsers:
https://developer.mozilla.org/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL
Solution 4
The straight answer is no. Javascript does not provide any means of validating certificates. This is a job left to the browser.
A better approach to this problem is from the server side. If you are controlling the site, than you can render down a variable on the page with information gleaned on the server side.
In .Net something like
var canSecure = <%= MySiteHasSsl ? "true" : "false" %>;
if (canSecure) {
if (confirm("This site supports SSL encryption. Would you like to switch to a secure connection?")) {
location.href = "https://mysite.com";
}
}
Solution 5
Useful notice: navigator.clipboard
will be undefined
on Chrome browsers if there's no valid SSL certificate.
MB.
Updated on November 04, 2020Comments
-
MB. over 3 years
Is there a way to check in JavaScript if given a host its SSL certificate is valid? (non blocking)
In my case, I want to display: "you can also use https://.." if via JavaScript I can make a request to
https://my_url
without being asked to accept an untrusted certificate.Can this be done asynchronously?