airsoftFreak
airsoftFreak

Reputation: 1608

Authentication with iOS/Swift

I have a very simple question, I have a node.js/express server that will handle backend authentication part, it is using token not cookies, the server part is working correctly, whenever someone register/login it would return with a JSON web token.

For example:

{
    "token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdW"
}

I'm using Alamofire to handle the HTTP request from iOS itself. The real question lies is how do I persist the token in the iOS/Swift itself?

What is the simplest way to do this?

Upvotes: 0

Views: 1493

Answers (3)

Shadowman
Shadowman

Reputation: 12079

The simplest way may be NSUserDefaults, but the most secure way would be to store the token in the iOS Keychain. Note there are several wrapper libraries (for example) available to make working with the keychain easier in Swift. The API can be a bit intimidating at times.

Upvotes: 0

Tom el Safadi
Tom el Safadi

Reputation: 6796

The simplest way is to store it in NSUserDefaults like this:

Writing:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Your Variable Value", forKey: "token")

Reading:

let defaults = NSUserDefaults.standardUserDefaults()
if let token = defaults.stringForKey("token") {
    print(name)
}

Upvotes: 0

paulvs
paulvs

Reputation: 12053

You should use the iOS Keychain to save sensitive information.

You should not use NSUserDefaults to store an authentication token or any other potentially sensitive information. It's unencrypted and easily accessible on a rooted device.

How would you like someone getting your authentication token and making requests to your private API at will (e.g. on the command line using curl)?

I've used the KeychainAccess CocoaPod and its usage is simple:

static let keychain = Keychain(service: "com.example.myapp")
keychain["secret_code"] = secretCode     // Save something
let secretCode = keychain["secret_code"] // Retrieve something

Upvotes: 4

Related Questions