I wanted to use aiohttp.request in order to get Reddit post, but when I ran the code it gives me this error, any possible solution?
Code:
#command(name='meme')
#guild_only()
async def meme_cmd(self, ctx):
async with request("GET", "https://www.reddit.com/r/meme/", headers={}) as response:
data = await response.json()
print(data)
Error:
Command raised an exception: ClientConnectorCertificateError: Cannot connect to host www.reddit.com:443 ssl:True [SSLCertVerificationError: (1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname m
ismatch, certificate is not valid for 'www.reddit.com'. (_ssl.c:1123)")]
Related
When I run this it works and gives a valid reponse
private readonly Lazy<Jira> jiraClient = new Lazy<Jira>(() => Jira.CreateRestClient("https://jira...", "name", "pass"));
but when I try to run this I get an error.
Issue issue = await this.jiraClient.Value.Issues.GetIssueAsync(jiraId);
Error Message: The request was aborted: Could not create SSL/TLS secure channel
here is the answer
The request was aborted: Could not create SSL/TLS secure channel
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I want to get the certificate hash. But I have no idea how to get the server peer certificate. Either in the request or response. The server I send the request to sets the Connection close header, so the retrieving the original ssl socket in the response doesn't work.
Currently no way, sorry.
You can check a cert hash easy though: https://docs.aiohttp.org/en/stable/client_advanced.html#ssl-control-for-tcp-sockets
The following example uses SHA-256 fingerprint check:
fingerprint = b'...' # should be 64 bytes length hash (256/8)
r = await session.get('https://example.com',
ssl=aiohttp.Fingerprint(fingerprint))
I've come up with this solution/hack
import aiohttp
class WrappedResponseClass(aiohttp.ClientResponse):
def __init__(self, *args, **kwargs):
super(WrappedResponseClass, self).__init__(*args, **kwargs)
self._peer_cert = None
async def start(self, connection, read_until_eof=False):
try:
self._peer_cert = connection.transport._ssl_protocol._extra['ssl_object'].getpeercert(True)
except Exception:
pass
return await super(WrappedResponseClass, self).start(connection, read_until_eof)
#property
def peer_cert(self):
return self._peer_cert
session = aiohttp.ClientSession(otherargs..., response_class=WrappedResponseClass)
The following works for me with aiohttp 3.8.3:
async with aiohttp.ClientSession() as session:
r = await session.get('https://bbc.com')
cert = r.connection.transport.get_extra_info('peercert')
I want to send a request to this server via Apollo and get a query :
const client = new ApolloClient({
link: new HttpLink({
uri:'http://mfapat.com/graphql/mfaapp/'}),
cache: new InMemoryCache()
})
const FeedQuery = gql
query{
allFmr{
fmrId,
name,
studio,
bedRm1,
bedRm2,
bedRm3,
bedRm4
}
}
`
But I'm facing this error message:
Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1
at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)
....
But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?
Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.
To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:
As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.
Reading the specific error sent enables you to fix the bug.
To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.
EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.
Base on #eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors.
// On Apollo server
// Error handler
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
const { status } = err;
res.status(status).json(err);
};
app.use(errorHandler);
In my Cassandra config I have enabled user authentication and connect with cqlsh over ssl.
I'm having trouble implementing the same with gocql, following is my code:
cluster := gocql.NewCluster("127.0.0.1")
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: "myuser",
Password: "mypassword",
}
cluster.SslOpts = &gocql.SslOptions {
CertPath: "/path/to/cert.pem",
}
When I try to connect I get following error:
gocql: unable to create session: connectionpool: unable to load X509 key pair: open : no such file or directory
In python I can do this with something like:
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
USER = 'username'
PASS = 'password'
ssl_opts = {'ca_certs': '/path/to/cert.pem',
'ssl_version': PROTOCOL_TLSv1
}
credentials = PlainTextAuthProvider(username = USER, password = PASS)
# define host, port, cqlsh protocaol version
cluster = Cluster(contact_points= HOST, protocol_version= CQLSH_PROTOCOL_VERSION, auth_provider = credentials, port = CASSANDRA_PORT)
I checked the gocql and TLS documentation here and here but I'm unsure about how to set ssl options.
You're adding a cert without a private key, which is where the "no such file or directory" error is coming from.
Your python code is adding a CA; you should do the same with the Go code:
gocql.SslOptions {
CaPath: "/path/to/cert.pem",
}
So I created this test case (a mish mash of existing alamofire test cases):
func testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess() {
// Given
let expectation = expectationWithDescription("\(URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(serverTrust, policies)
// When
Alamofire.request(.GET, URLString)
.authenticate(user: user, password: password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertTrue(data?.length > 0, "Data not found.")
XCTAssertNil(error, "error should be nil")
}
The Root CA is a self-signed cert for an existing sight that works.
But I get this error back:
Test Suite 'Selected tests' started at 2015-08-12 12:46:37.512 Test
Suite 'StageAuthentication' started at 2015-08-12 12:46:37.514 Test
Case '-[Alamofire_iOS_Tests.StageAuthentication
testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess]'
started. 2015-08-12 12:46:37.663 xctest[3641:12220875]
NSURLSession/NSURLConnection HTTP load failed
(kCFStreamErrorDomainSSL, -9813)
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:309: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertNotNil failed - response should not be nil
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:310: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertTrue failed - Data not found.
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:311: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertNil failed: "Error Domain=NSURLErrorDomain Code=-1202 "The
certificate for this server is invalid. You might be connecting to a
server that is pretending to be “portal.care180.com” which could put
your confidential information at risk."
UserInfo={NSLocalizedDescription=The certificate for this server is
invalid. You might be connecting to a server that is pretending to be
“portal.care180.com” which could put your confidential information at
risk., NSLocalizedRecoverySuggestion=Would you like to connect to the
server anyway?, _kCFStreamErrorDomainKey=3,
NSUnderlyingError=0x7ae21c60 {Error Domain=kCFErrorDomainCFNetwork
Code=-1202 "(null)"
UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorCodeKey=-9813, _kCFStreamErrorDomainKey=3, kCFStreamPropertySSLPeerTrust=,
kCFStreamPropertySSLPeerCertificates={type = immutable, count = 1, values = ( 0 :
)}}}, _kCFStreamErrorCodeKey=-9813,
NSErrorFailingURLStringKey=https://portal.care180.com/services/init.json,
NSErrorPeerCertificateChainKey={type =
immutable, count = 1, values = ( 0 : )},
NSErrorClientCertificateStateKey=0,
NSURLErrorFailingURLPeerTrustErrorKey=,
NSErrorFailingURLKey=https://portal.care180.com/services/init.json}" -
error should be nil Test Case
'-[Alamofire_iOS_Tests.StageAuthentication
testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess]'
failed (0.156 seconds). Test Suite 'StageAuthentication' failed at
2015-08-12 12:46:37.671. Executed 1 test, with 3 failures (0
unexpected) in 0.156 (0.157) seconds Test Suite 'Selected tests'
failed at 2015-08-12 12:46:37.672. Executed 1 test, with 3 failures
(0 unexpected) in 0.156 (0.160) seconds Program ended with exit code:
1
Sorry for being dense: what am I doing wrong? Or is there an Alamofire test that does this with a different cert and host?
I confused the root and the leaf. My bad.