How to authenticate Ios Server-to-Server Notifications - ios

When we configure Server-to-Server Notifications, we Specify our secure server's URL in App Store Connect and the apple server communicates on that URL. but is there a way to authenticate this request?
It is not safe to keep url open without authentication
in case of PlayStore we can use GOOGLE_DEVELOPER_API_KEYFILE_JSON for authentication, but how to do this for iOS server-server notification?

As the comments have already clarified that there is no built in way.
So, here is my work around of this problem.
Apple sends password in the notification which is App secret key which ideal should only be known by API and Apple.
And to verify receipts coming from the App this password must already be stored somewhere (configuration?) in the API.
So I suggest to check whether the password in request matches with the one stored in our API?
If yes then this is a valid request.
If not then it may be sent by a hacker.
My only concern is that does this App shared secret key aka password change? by Apple or developer? If not than this is the solution.

One way to do it is to use Basic auth. As you cannot specify a header you can use the url format: https://username:password#SERVER_ENDPOINT. This will automatically encode the username:password and construct a basic auth header with the encoded string.
Source:
https://en.wikipedia.org/wiki/Basic_access_authentication

Related

Apple Sign-In: How to use it for custom server endpoint authentication?

My use case is that once I have a user signed into my app, I use the Oauth token, resulting from the sign-in, when I make endpoint calls from my app to my custom server-- to authenticate the caller. E.g., I use Google Sign In in this way.
This method (e.g., with Google Sign In) has several useful properties:
Updated tokens are created automatically on the client app.
My custom server can easily verify the validity of the token, using Google's endpoints.
Initial token verification can take place early in the endpoint request processing-- without access to the custom servers database (as in the style in https://github.com/IBM-Swift/Kitura-Credentials).
My question is: Given that we're being told we have to incorporate Apple Sign-In into our iOS apps (if we offer general purpose sign-in facilities), how can I do endpoint authentication with my custom server?
I see two alternatives, neither of which I like very much.
First, I can have my client app send an Apple Sign In id_token to my server and ignore the exp (expiry) field. I can regenerate the id_token periodically (apparently, no more than once a day) and send it back to my client. I don't like this idea both because of ignoring the expiry of the token, and because of the need to periodically send the token from server to client. (My app uses multiple sign in systems and this just creates extra difficulty).
Second, I could have my client send an Apple Sign In refresh token to my server. My server would need, of course, to initially generate that refresh token and send it back to the client. I like this idea even less than the first idea. My initial token verification in my custom server would need to access its database to look for a match this token. I can't generally use an Apple endpoint -- because, again, Apple is apparently going to throttle this verification.
Additionally, I don't really like the idea that my custom server can, at best, check on token validity once a day. If the user revokes the app's credentials, I would hope my custom sever would stop being able to operate on behalf of the user relatively quickly.
Thoughts?
10/5/19-- update to the first alternative above. Upon actual use of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens for refresh token validation, I find that it is not actually generating an updated id token. It is generating an access token (but Apple doesn't define a use for that), and is validating the refresh token. And so, there is no way to send an updated id token to the client iOS app. Thus, using the first alternative, the expiry date of the id token cannot be used.
10/10/19-- update: I've written a blog article on this subject-- https://medium.com/#crspybits/apple-sign-in-custom-servers-and-an-expiry-conundrum-d1ad63223870
8/6/20-- update: Follow on blog article with possible path forward, pending details from Apple: https://medium.com/#crspybits/part-ii-apple-sign-in-custom-servers-and-an-expiry-conundrum-b3e9735dc079
In Get the most out of Sign in with Apple in WWDC 2020, at 11:30 in their presentation, they introduce server-to-server notifications to enable your server to monitor user account state changes on a real-time basis.
So far, few details on this though.
----------------- UPDATE (12/23/20) -----------------
I now have these server-to-server notifications working in a testing environment with my server. Some notes:
I decided on the endpoint to use, on my server, to allow Apple to send my server these REST endpoint requests.
I pasted that into developer.apple.com > Account > Certificates, Identifiers & Profiles > Identifiers > Select your app identifier > Click 'Edit' next to 'Sign In with Apple' > Server to Server Notification Endpoint
This endpoint is effectively unauthorized. E.g., it is made by Apple with no OAuth credential access to your server. How this is setup will depend on your server. I had a means to set up a new endpoint/route for my server that was unauthorized.
I have the client side and other parts of my server set up to allow creation of accounts using Apple Sign In. So, using one of those accounts, I now started taking actions that would cause Apple to invoke their server-to-server notification endpoint on my server. I wanted to reverse engineer the details of the endpoint request Apple is making, since details are scarce.
This provides some ideas on how to cause the notification events to occur:
How to revoke Sign in with Apple credentials for a specific app?
You can revoke credentials, but it's easier (because you can do it repeatedly) to enable and disable the email relay. Of course, to do this, you have to initially sign-in with Apple using the private/email relay.
I next learned two things:
a) After you take the action (e.g., revoke the email relay), the server-to-server notification endpoint is accessed on your server within about 30 seconds. I had added various log output into my server, so could watch my server log and see this happening.
b) The endpoint request Apple makes to your server has body data containing JSON in the following format:
{"payload" : "-- SNIP -- JWT"}
I'm using the following Swift structure to decode this.
struct ApplePayload: Decodable {
let payload: String // JWT
}
As Apple has indicated in the WWDC 2020 video (https://developer.apple.com/videos/play/wwdc2020/10173/), the main content of the body data is a JWT. Above, this is the value of the key "payload" in the JSON.
The next step is decoding this JWT. I just guessed that it would use the same mechanism for decoding as with the JWT in other parts of the Apple Sign In server-side process. And specifically, in decoding the identity token (a JWT) passed up to your server by a client using Apple sign in. See https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple
I had some code that did this JWT decoding, so I factored that out and put it in a common place:
https://github.com/SyncServerII/AppleJWTDecoder.git
Integrating that into my server-side processing of Apple's server-to-server notification requests, I found that indeed this JWT can be decoded in this manner.
Another aspect that became evident is that the structure indicated by Apple in the WWDC 2020 video isn't 100% what is present in the JWT, after decoding. Specifically, in my tests so far at least the events field is not an array, rather it has a single value. See https://github.com/SyncServerII/AppleJWTDecoder/blob/main/Sources/AppleJWTDecoder/AppleSignInClaims.swift for a Swift structure.
I am now successfully parsing the JWT. The next main step on my server is to actually utilize the different event types in my server to take actions. For me this is going to involve the two account (not email) related actions:
User decided to stop using their Apple Id with your application. And
should be treated as a sign-out by the user. E.g., when a user decides
to disconnect your application from Settings. (From
https://developer.apple.com/videos/play/wwdc2020/10173/)
Also considered a request from user to "delete their app account"
(broader context: "Server to Server Notification Endpoint Sign in with
Apple server to server notifications allow you to receive important
updates about your users and their accounts. Notifications are sent
for each app group when users change mail forwarding preferences,
delete their app account, or permanently delete their Apple ID. Each
group of apps can have one URL, which must be absolute and include the
scheme, host, and path. TLS 1.2 or higher is required to receive
notifications. Learn more.") To see these docs, go to:
developer.apple.com > Account > Certificates, Identifiers & Profiles >
Identifiers > Select your app identifier > Click 'Edit' next to 'Sign
In with Apple' > Server to Server Notification Endpoint
case consentRevoked = "consent-revoked"
User has asked Apple to delete their Apple Id. The user identifier will now no longer be valid.
case accountDelete = "account-delete"
My plan is to take both of these events as equivalent- and delete the user's account on my server. I'm then going to have to consider how to communicate this to my client (iOS app). It will need to know that the user has deleted their account.

Validating jwt on native platforms

I'm building an native iOS app, it uses OAuth 2.0/OIDC for authentication and authorisation. The auth server is identity serverver 4.
By going thru documents such as https://www.rfc-editor.org/rfc/rfc8252 I have established that the correct flow to use is "authorisation code" flow even though we own the app, the auth server and the resources.
I also learned that we need to use a secure browser such as SFSafariViewController and that we need to use PKCE and remember to use the "state" key in the request and validate on return.
My problem is validating the jwt on the iOS device. I use https://github.com/kylef/JSONWebToken.swift as suggested on jwt.io
To validate the validity of the jwt we need to check that it was is deed signed by our auth server. The server signs using an async rs256 key and exposes the public key on a endpoint. JSONWebToken.swift does not support rs256 and I have not been able to find any iOS library that does, so how to other people validate jwt on iOS devices? I guess we could swith to HS256 which is supported by JSONWebToken.swift but this is a sync algorithm and would require us to store the key on the device which would not be safe.
How to solve this issue, surely I'm not the only one having it...
You could use the Vapor package at https://github.com/vapor/jwt which does support RS256, but you'll need to fetch the JWK yourself.

How to throw facebook token to own server securely?

I'm developing iOS app(Swift) using 3rd party(facebook) authentication. I encountered a question which is how I can throw the access token from facebook to my own server.
I've been writing something like below..
Alamofire.request(.POST, "https://example.com/user/fb", access_token: facebook_access_token)
but I'm not sure this is safe enough.
Not only that, when I implement email/password login as well, I've been writing something like below..
var user = [email: "ex#mple.com", pass: "password"]
Alamofire.request(.POST, "https://example.com/user/", user: user)
Are those safe enough? Or if there're best practices please let me know.
Thanks!
Sending your credentials via SSL prevents others from reading the values in the middle. So, it's theoretically secure. ie: It goes through the security provided by the transport layer.
However, it's not the recommended approach to send plaintext passwords to the server. The correct way is to hash the password at each client, then send the hash value to the server. At the server, you should compare whether the hashes match. You might need to do some changes to your server logic. But, in the long run, it should be worth.
I assume you are asking whether its safe to send it over the network. If you are using SSL encrypted URL and pinning the SSL to your app then yes it is. Here is blog post explaining how to do SSL pinning on IOS
https://possiblemobile.com/2013/03/ssl-pinning-for-increased-app-security/

Sending Device Token Safely for APNs

For iOS applications that require push notifications, it must first request the user for permission to do so. After that, a device token is generated and with this, the remote server may communicate to the user through this token.
I have read a similar question here and I do not feel it is enough. The picture below is a trusted certificate, it allows me to view all traffic that happens on this device.
With Fiddler2 as well as CertMaker, I can sniff HTTPS traffic, which means the client can probably know what data they are sending, and to where.
My question is, knowing that SSL is not secure from protecting my clients from seeing what I send to the remote server, should I simply encypt with a secret key found within my application?
Such as encrypt("device_token","secretkey_a0a0a0a") (pretend this is Objective-C)?
Couldn't someone just find that key within my application? I also read this question, and it seems that it would be possible to get back the secret key.
My plan for this goes like this:
Within the iOS application, Generate a random string named activate.
Encrypt (not hash), the token by the random string and a secret key that I only know. (secretkey_a0a0a0)
Send the encrypted string along with the generated randomly generated string (active).
Within serverside, I check if I can decrypt a valid token from using the active and my secret key.
I save the token in my database if it is valid.
This prevents people from random entering tokens yes, however, secretkey_a0a0a0 is a string literal. It's very possible to get this within the application binary itself.
My question is, how do I protect this secret key? The answer can also be, how can I prevent people from sending invalid tokens to my server as well.
I have heard of encryption, but doesn't that only apply to resource files?
How should I approach this?
If you do SSL-Pinning ( AFNetworking has this implemented ) you won't be able to (in a reasonable timeframe) sniff the https traffic between the client and server if you don't have the servers private key.
If your fear is that man in the middle can steal your token and send fake push notifications to users of your application, be sure that this cant happend. Since requests to apple apn servers must be signed with pem file, the main concern should be how to keep certificate file secured, and not apn token. If you want to prevent writing invalid tokens in your database then you should implement some CRC or odd/even bit mechanism.
You might want to check the security section in the Push Notifications Guide, in particular the section titled "Token Generation and Dispersal".
The device token is generated by the device connecting through the Apple's APNS. My guess (they don't say in the docs) is that it's unique for a given app identifier.
The APNS then will probably match those identifiers with the pem certificate you use to communicate with it thus validating that the push notifications are actually originating from your app.
Encrypting the device token seems overkill in this scenario.
To prevent someone maliciously spamming your server with tokens, I would hash the token when a secret key and send both the token and the hash to the server. You can then hash the token again on the server, with your secret key, and check that the request is valid.

Authenticating against a REST API with iOS client using Facebook SSO as the only login mechanism

I'm planning to use Facebook as the only sign-on mechanism for an application that I'm building and need some feedback on the design. Here it goes -
User opens the app and is presented with a register screen. The facebook authorization flow starts and let's assume it succeeded and the user has successfully registered himself. Upon success, the app calls the Facebook graph API and gets the user's firstname, lastname, email, date of birth etc. With this data, the app then calls a web service method called RegisterUser(string Fullname, string FirstName, string LastName ...) which creates the user record in the database.
Now for subsequent calls to the API, I need to authenticate that the request is really coming in from my application (not necessarily a particular user). I've looked up the S3 REST API and it seems that with every request there's a HTTP header called Authorization that the client creates by appending a bunch of other HTTP Headers like Date, Method, Request data, signing it with the client's private key and computing its base64 encoded value. This is verified on the server side to authenticate the client.
Now, I'm comfortable implementing all this, but a few questions:
If I have a private key, is it safe to include it as a part of the iOS application itself? Can someone extract the key from the iOS application binary? If so, how do I deal with this?
Are there any other changes you'd make to this design ?
Thanks,
Teja.
Make sure you apply a one-way hashing algorithm to the value to base64 encode - base64 is a two-way encoding, so you don't want eavesdroppers reverse engineering your private key from that. Amazon S3 does this with performing a SHA-1 before doing the base64.
As with all (AFAIK?) compiled binaries, your app shouldn't be able to be decompiled.

Resources