How to resolve iOS SSO Auth failure with 1000 code? - ios

I am going to implement SSO Auth to our enterprise application. I watched this WWDC talk. There is not enough information. I tried to use a simple code from this talk like this:
let url = URL(string: "realm://{{identity_server_url}")! //I checked this by changing realm: to https:.
let ssoProvider = ASAuthorizationSingleSignOnProvider(identityProvider: url)
let request = ssoProvider.createRequest()
request.requestedOperation = .operationLogin
let authController = ASAuthorizationController(authorizationRequests: [request])
authController.delegate = self
authController.presentationContextProvider = self
authController.performRequests()
self.ssoProvider = ssoProvider
self.authController = authController
But this is always failed with this error description:
Error Domain=com.apple.AuthenticationServices.AuthorizationError Code=1000 "(null)"

Related

MSAL and IOS - Can't figure out the authority for my B2C instance

I have created a B2C instance called myB2CDemonstration and there I created a Experience Framework flow called B2C_1A-SIGNUP_SIGNIN.
My code looks like this:
let kClientID = "d7628 ... 4a34d"
let kGraphEndpoint = "https://graph.microsoft.com/"
let kAuthority1 = "https://login.microsoftonline.com/7fb6a ... 427"
let kAuthority2 = "https://myB2CDemonstration.b2clogin.com/myB2CDemonstration.onmicrosoft.com/B2C_1A_SIGNUP_SIGNIN"
let kAuthority3 = "https://myB2CDemonstration.onmicrosoft.com/7fb6a ... 427"
let kRedirectUri = "msauth.br.com.edenred.ticket://auth"
let kAuthority = kAuthority1 // or 2 or 3
guard let authorityURL = URL(string: kAuthority) else {
self.updateLogging(text: "Unable to create authority URL")
return
}
let authority = try MSALAADAuthority(url: authorityURL)
let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID,
redirectUri: kRedirectUri,
authority: authority)
msalConfiguration.knownAuthorities = [authority]
self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
self.initWebViewParams()
if I use kAuthority1 or kAuthority2 I get the error
Could not acquire token: Error Domain=MSALErrorDomain Code=-50000
UserInfo={MSALErrorDescriotionKey=AADSTS50049: Unknown or invalid instance.
MSALOAutherrorKey=invalid_instance, MSALInternalErrorCOdeKey=-42010}
(and a bunch of trace ids e correlation ids and etc)
if I use kAuthority3 I get the error
The operation couldn’t be completed. (MSIDErrorDomain error -51112.)
TID=3929455 MSAL 1.2.5 iOS Sim 16.2 [2023-01-05 20:48:01] Creating Error with description: Trying to initialize AAD authority with B2C authority url.
can anyone tell me what im doing wrong?
Try the sample here, you seem to be using an AAD sample. https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-ios-app
I actually got it myself: I changed the MSALAADAuthority to MSALB2CAuthority and removed the scopes and used the variant 2 (with name of tenant and no GUIDs)

Unable to connect to remote RabbitMQ server using Swift

I am using RabbitMQ in my app for chat module. It works fine with local server but somehow I am not able to connect to remote RabbitMQ server. I keep getting this error when I try to send a message.
Received connection: <RMQConnection: 0x6000022e2eb0>
disconnectedWithError: Error Domain=GCDAsyncSocketErrorDomain Code=7
"Socket closed by remote peer" UserInfo={NSLocalizedDescription=Socket
closed by remote peer}
My swift code looks like this:
func getRabbitMQUrl() -> String{
var components = URLComponents()
components.scheme = "amqps"
components.host = "[broker-id].mq.[region].amazon.aws.com"
components.user = "[username]"
components.password = "[passowrd]"
components.port = 5671
let url = components.url?.absoluteString ?? "-"
print("RabbitMQ URL", url)
return url
}
let uri = getRabbitMQUrl()
let conn = RMQConnection(uri: uri, delegate: RMQConnectionDelegateLogger())
conn.start()
let ch = conn.createChannel()
let q = ch.queue(UUID().uuidString, options: .durable)
let exc = ch.direct("my-exchange-name-here")
q.bind(exc, routingKey: "my-routing-key")
q.subscribe({(_ message: RMQMessage) -> Void in
print("Message received")
})
While using the local server, I set the uri "amqp://[username]:[password]#localhost:5672" and this works as expected.
PS: when I set this subscriber I do not get any error message regarding connection or anything. so I think it is connecting to the server without any issue.
But, when I send a message from the iOS app, the backend publish it and so the iOS app should receive it back. Exactly at this time, it gives me the above error!
EDIT: Though the C# backend is able to publish and subscribe messages successfully with RabbitMQ remote server. It is just the iOS client who fails!
Any help would be appreciated!
After going through a lots of links, slack channels and Github issues, finally the issue has been resolved! The solution was unexpected.
The problem was, my C# backend has set the vhost to a slash / and in my Swift code I was passing an empty string instead. I got hint from here
I made these 2 changes in my code:
In server uri I added %2f(a slash /) as the vhost at the end.
I set the options of the exchange also to .durable just like the queue
Here is the complete working code:
func getRabbitMQUrl() -> String{
var components = URLComponents()
components.scheme = "amqps"
components.host = "[broker-id].mq.[region].amazon.aws.com"
components.user = "[username]"
components.password = "[passowrd]"
components.port = 5671
components.path = "/%2f" //1st change
let url = components.url?.absoluteString ?? "-"
print("RabbitMQ URL", url)
return url
}
let uri = getRabbitMQUrl()
let conn = RMQConnection(uri: uri, delegate: RMQConnectionDelegateLogger())
conn.start()
let ch = conn.createChannel()
let q = ch.queue(UUID().uuidString, options: .durable)
let exc = ch.direct("my-exchange-name-here", options: .durable) // 2nd change
q.bind(exc, routingKey: "my-routing-key")
q.subscribe({(_ message: RMQMessage) -> Void in
print("Message received")
})
Your URI is AMQP on the local host but AMQP is the example code.
You should connect to port 5671 if you are using AMQPS (And 5672 if you are on AMQP) Try that!

iOS - TunnelKit OpenVPNTunnelProvider ProviderConfigurationError

I am trying to create an ios vpn client using Tunnelkit. I am following this tutorial.
https://github.com/passepartoutvpn/tunnelkit
am able to compile and run the application, but when I try to connect, the app crashes and throwing.
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error:
TunnelKit.OpenVPNTunnelProvider.ProviderConfigurationError.credentials(details:
"keychain.set()")
Anyone who had already set up tunnel kit OpenVPN, please help to resolve this issue.
func connect() {
let server = textServer.text!
let domain = textDomain.text!
let hostname = ((domain == "") ? server : [server, domain].joined(separator: "."))
let port = UInt16(textPort.text!)!
let socketType: SocketType = switchTCP.isOn ? .tcp : .udp
let credentials = OpenVPN.Credentials(textUsername.text!, textPassword.text!)
let cfg = Configuration.make(hostname: hostname, port: port, socketType: socketType)
let proto = try! cfg.generatedTunnelProtocol(
withBundleIdentifier: tunnelIdentifier,
appGroup: appGroup,
credentials: credentials
)
let neCfg = NetworkExtensionVPNConfiguration(title: "new title", protocolConfiguration: proto, onDemandRules: [])
vpn.reconnect(configuration: neCfg) { (error) in
if let error = error {
print("configure error: \(error)")
return
}
}
}
You need to follow the integration steps.
https://github.com/passepartoutvpn/tunnelkit#demo
Enable App Groups and Keychain Sharing capabilities
make sure the appGroup value is the same which you set in your target/Signings & Capabilities/App Groups

Could not load module: CTLS

I import JWT(using .Package(url:"https ://github.com/vapor/jwt.git", majorVersion: 1))
enter image description here
The project can build and run. But when I look into CTLS, the Xcode shows "Could not load module: CTLS". I don't know why.
At the same time, the JWT I create seems not right. Here is my codes:
import JWT
import Vapor
get("token") { req in
let algValue = StructuredData.string("ES256")
let kidValue = StructuredData.string("CapExedKid")
let headerData = StructuredData.object(["alg":algValue,"kid":kidValue])
let header = JSON.init(headerData)
let issValue = StructuredData.string("CapExdTeam")
let sec = Int(Date().timeIntervalSince1970)
let iatValue = StructuredData.number(StructuredData.Number(sec))
let expValue = StructuredData.number(StructuredData.Number(sec+1000000))
let claimsData = StructuredData.object(["iss":issValue,"iat":iatValue,"exp":expValue])
let claims = JSON.init(claimsData)
let url = URL.init(fileURLWithPath: "/Users/aamac/Desktop/HelloWorld/AuthKey_demoKey.p8")
let data = try Data.init(contentsOf: url)
let signer = ES256.init(key: data.makeBytes())
let jwt = try JWT.init(headers: header, payload: claims, signer: signer)
let token = try jwt.createToken()
return token }
I use the token to do the authenticate requests as Apple Music API says, I got a http status code 500..
I enter this in terminal:
curl -v -H 'Authorization: Bearer [developer token]' "https ://api.music.apple.com/v1/catalog/us/songs/203709340"
and got 500..
But I use a Python library to get the token and do the request in terminal, it works, so I doubt that the JWT in swift have some kind of problem...Can anyone tell me??
I experienced a similar problem (https://github.com/vapor/jwt/issues/47). What worked for me was using data.bytes.base64Decoded instead of data.makeBytes() when initializing the signer.

iOS: Twitter update profile api giving error

I am trying to access update profile api of twitter. But its giving error.
let conn = WebserviceConnectionManager(serviceTokenId: "Twitter profile")
let url = NSURL(string: "https://api.twitter.com/1.1/account/update_profile.json")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let oAuthToken = FHSTwitterEngine.sharedEngine().accessToken.key
let oAuthTokenSecret = FHSTwitterEngine.sharedEngine().accessToken.secret
request.addValue(oAuthToken, forHTTPHeaderField:"oauth_token")
request.addValue(oAuthTokenSecret, forHTTPHeaderField:"oauth_token_secret")
conn.delegate = self
conn.startConnection(request)
Callback method gives me following error:
errors = (
{
code = 215;
message = "Bad Authentication data.";
}
);
Any help would be highly appreciated.
Since Twitter's API 1.1 does not allow access without authentication, because you have to use access tokens and secret keys; all requests must be made with a server-side script.
follow steps here and you will fixed your problem.

Resources