Alamofire SSL failure - swift

I know this type of question has been asked many times but it seems like there is an answer but I can not get it working.
In my environment, production is the only place I have a valid SSL certificate. Using Alamofire in my iOS app built against production works great. I don't want to develop/test against production and we can't get a valid SSL cert right now for any other environment.
I found this SO answer from an Alamofire developer suggesting a way to solve this but it is not working for me. When I run my app against non-production, the failure I'm seeing implies that it is using NSURLConnection and not NSURLSession as the proposed solution seems to rely on.
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Would love it if someone could share their solution (maybe a gist?) on this.

I finally figured it out. The SO answer I had referenced had a small but important bug in it. I submitted an edit for it but will post the working code here:
let manager = Alamofire.Manager.sharedInstance
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = NSURLSessionAuthChallengeDisposition.UseCredential
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
return (disposition, credential)
}
The issue was that it was not using the singleton instance of Alamofire.Manager. Instead it was creating a brand new instance which was never being used by the Alamofire framework.

Related

AddOAuth is not defining the Callbackpath specified (getting a 404 on it) - ASP .NET Core 3

I am trying to implement an OAuth2 client using ASP.NET Core 3 application. Here is how I add OAuth to my startup
services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = "Client.Auth.Cookie";
config.DefaultSignInScheme = "Client.Auth.Cookie";
config.DefaultChallengeScheme = "SelfServer";
})
.AddCookie("Client.Auth.Cookie")
.AddOAuth("SelfServer", config =>
{
config.CallbackPath = "/oauth/callback";
config.AuthorizationEndpoint = "https://Server/oauth/authorize";
config.TokenEndpoint = "https://Server/oauth/token";
config.ClientId = "clientid";
config.ClientSecret = "secret_key";
});
As I read in the documentation, the /oauth/callback is something I do not have to define myself (no need to create OAuthController with Callback action). I kind of by mistake did it and defined it myself, then when I realized, I deleted the OAuthController and now I am getting a 404 on https://client/oauth/callback.
What am I missing?
Alright I realized a few seconds after posting this question that I forgot to call
app.UseAuthentication()
in my Configure() method in the Startup.

Firebase new user: Identity Toolkit API error

I'm using Firebase auth with swift 4.
I create a new user like this
Auth.auth().createUser(withEmail: emailTextField.text!, password: "abc123!") { (authResult, error) in
// [START_EXCLUDE]
guard let email = authResult?.user.email, error == nil else {
print(error!)
print("NO!!!!!!")
return
}
print("\(email) created")
// [END_EXCLUDE]
guard let user = authResult?.user else { return }
}
But I get this error:
domain = usageLimits;
extendedHelp = "https://console.developers.google.com";
message = "Identity Toolkit API has not been used in project *** before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=**** then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.";
reason = accessNotConfigured;
I have enabled identity toolkit API through this link, and it still doesn't work.
I have enabled email and password sign in providers in firebase console.
I deleted firebase project and remade it, and redownloaded the googleservice.plist.
It still doesn't work. I've been hours on it!
Thanks so much,
I have enabled identity toolkit API through this link, and it still doesn't work.
I went back to there, disabled the API, then re-enabled it, and it worked.

Unit testing NancyFX API - ConfigurableBootstrapper Exception

Im trying to get nunit test setup for my Nancy API. I have a very simpLe end point:
this.Get["/"] = _ =>
{
return Negotiate
.WithModel(" API is running")
.WithStatusCode(HttpStatusCode.OK);
};
When I try to test it with this test:
this._browser = new Browser(with => {
with.Module(new IndexModule());
});
var result = this._browser.Get("/", with => { with.HttpRequest(); });
Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));
I get ConfigurableBootstrapper Exception and with message of "OhNoes".
If I change the return to:
return "API is running";
It works. I think I might be missing something in the test setup to allow the negotiated return.
Does anyone have an idea of what I'm doing wrong? Thanks.
There will be a clue in the "Oh Noes" exception - probably something like;
Nancy.ViewEngines.ViewNotFoundException
Try adding
with.Header("Accept", "application/json")
or similar to your request setup. By default I think the testing browser requests HTML content, which Negotiate will want to render in a view. See here https://github.com/NancyFx/Nancy/wiki/Content-Negotiation under the section "Default response processors"

How to authenticate a gRPC call for the Assistant SDK?

I'm using the Swift gRPC library (which curiously isn't listed on gRPC's website, but there is a GitHub repo for it) to build an implementation of the Google Assistant SDK for macOS. I've gotten my OAuth2 credentials and token, and am trying to make the initial request to begin a conversation, however it fails to do so.
I always get the error Google_Assistant_Embedded_V1Alpha1_EmbeddedAssistantClientError error 1.) and gRPC.CallError error 1.
I ran Wireshark to try and debug the issue, and I saw the my computer is attempting to establish a connection but eventually ends up aborting the connection. I think it may be due to a TLS issue, but I'm not sure if that actually is the case or how to fix it.
I noticed the service initialization function has an overload where you specify certificates, but I don't know what to put there (or if that function needs to be used at all)
typealias AssistantService = Google_Assistant_Embedded_V1Alpha1_EmbeddedAssistantService
typealias AssistantCall = Google_Assistant_Embedded_V1Alpha1_EmbeddedAssistantConverseCall
typealias AudioInConfig = Google_Assistant_Embedded_V1alpha1_AudioInConfig
typealias AudioOutConfig = Google_Assistant_Embedded_V1alpha1_AudioOutConfig
typealias ConverseRequest = Google_Assistant_Embedded_V1alpha1_ConverseRequest
typealias ConverseConfig = Google_Assistant_Embedded_V1alpha1_ConverseConfig
var service: AssistantService?
var currentCall: AssistantCall?
public init() {
service = AssistantService(address: Constants.ASSISTANT_API_ENDPOINT)
let token = "Bearer \(UserDefaults.standard.string(forKey: Constants.AUTH_TOKEN_KEY)!)"
service?.metadata = Metadata(["authorization" : token])
}
func initiateRequest() {
var request = ConverseRequest()
request.config = ConverseConfig()
var audioInConfig = AudioInConfig()
audioInConfig.sampleRateHertz = 16000
audioInConfig.encoding = .linear16
request.config.audioInConfig = audioInConfig
var audioOutConfig = AudioOutConfig()
audioOutConfig.sampleRateHertz = 16000
audioOutConfig.encoding = .linear16
audioOutConfig.volumePercentage = 50
request.config.audioOutConfig = audioOutConfig
do {
currentCall = try service?.converse(completion: { result in
print("Result code \(result.statusCode)")
print("Result description \(result.description)")
print("Metadata \(String(describing: result.initialMetadata))")
print("Status message \(result.statusMessage ?? "Error")")
print("Obj description \(String(describing: result))")
print("result \(result)")
})
try currentCall?.send(request) { err in
print("Error in initial request: \(err)")
}
} catch {
print("Initial error \(error)")
}
}
This is what the Wireshark for it looks like, if it is any help:
I had to add the roots.pem file found here to my project and use it as follows:
let u = Bundle.main.url(forResource: "roots", withExtension: "pem")!
let certificate = try! String(contentsOf: u)
let token = "Bearer \(UserDefaults.standard.string(forKey: Constants.AUTH_TOKEN_KEY)!)"
service = AssistantService(address: Constants.ASSISTANT_API_ENDPOINT, certificates: certificate, host: nil)
service?.metadata = Metadata(["authorization" : token])
Please see some new examples in the grpc-swift project that call Google Cloud APIs. I've simplified client creation to use TLS by default and to embed a default roots.pem in the library binary. You can see that here along with usage of an auth library that supports Google Application Default Credentials.
I don't know Swift, and your Wireshark screen shot may be masking important information, but I believe one or both of the following may be the problem:
Constants.ASSISTANT_API_ENDPOINT needs to be set to "embeddedassistant.googleapis.com". (It isn't clear, but I don't think the destination address shown in Wireshark is the API endpoint, which it should be.)
Constants.AUTH_TOKEN_KEY should be the auth token that you've gotten as part of the OAuth2 dance. Keep in mind that it expires (usually after an hour) and you'll need to get a new one. I don't know how Swift configuration works for it, but in others you don't need to specify the "Bearer" part of the auth information since you're not passing the header specifically.
Took the latest
pod 'SwiftGRPC'
pod 'SwiftProtobuf'
version using pod update and it got fixed .
Installing BoringSSL 10.0.6 (was 10.0.5 and source changed to https://github.com/CocoaPods/Specs.git from https://github.com/cocoapods/specs.git)
Installing SwiftGRPC 0.5.1 (was 0.4.3 and source changed to https://github.com/CocoaPods/Specs.git from https://github.com/cocoapods/specs.git)
Installing gRPC-Core 1.12.0 (was 1.11.0 and source changed to https://github.com/CocoaPods/Specs.git from https://github.com/cocoapods/specs.git)
Installing Realm 3.7.6 (was 3.7.4 and source changed to https://github.com/CocoaPods/Specs.git from https://github.com/cocoapods/specs.git)
Installing RealmSwift 3.7.6 (was 3.7.4 and source changed to https://github.com/CocoaPods/Specs.git from https://github.com/cocoapods/specs.git)
Then all i need was create the session/service with my certificate.
let certPath = Bundle.main.url(forResource: "XYZ", withExtension: "pem")!
let certificate = try! String(contentsOf: certPath)
service = Pronounce_PronounceServiceClient(address: Constants.ServerApi.grpcBaseUrl, certificates: certificate)

socket.io for react native (sending query problems)

I'm using this library and i can connect without problems.
Usually when I have worked with sockets the code that ever i used is:
socket = io.connect(url, { query: ‘token=’ + token});
and i can see this info reading socket.request._query
Using socket.io for react native i'm trying to send params:
this.socket = new SocketIO('http://localhost:3000', { query: ‘token=’ + token});
but in socket.request._query only can see this log:
{ transport: 'polling', b64: '1' }
In the library some options are mentioned like: connectParams. But i don't know how i can see the info
Related: link
It's not pretty detailed in the repo, but connectParams is a key/value object, and furthermore the values you sent in it will be appended in the url, as shown here:
if connectParams != nil {
for (key, value) in connectParams! {
let keyEsc = key.urlEncode()!
let valueEsc = "\(value)".urlEncode()!
queryString += "&\(keyEsc)=\(valueEsc)"
}
}
>Source<
So, you should try using connectParams like this(though I'm not sure how you tried it before):
this.socket = new SocketIO('http://localhost:3000', {
connectParams: {
myAwesomeQueryStringParam: "someRandomValue"
}
});
PS: forgive me, my english is pretty bad