2

I have a working Facebook login in my Swift app. I also have a backend server with which I want to communicate.

I am wondering how would I go about authenticating those API requests so that my app knows what person made that request.

Now, I know this is most likely done via tokens. Should I just randomly generate a string (token) when a new user logins via Facebook and then make a "registration" request to my API with said token so that it gets saved into database and I can use it from now on?

I do not want to use third-party services like Parse since I need my own backend anyways for purposes of this app.

  • This seems to be the solution to my problem http://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we – Filip ヅ Hájek Feb 26 '15 at 09:17

1 Answers1

0

Use Core Data, creating an entity called "User" or whatever you like with attributes "access_token" and any other variables you need to keep in memory to authenticate.

@objc class User: NSManagedObject {
    @NSManaged var access_token: String?
}

Create a helper function to save Core Data, passing in your authentication variables when they're returned from the server:

save("User", [
    "access_token": accessToken
])

func save(entity: String, _ attributes: [String: AnyObject]) -> NSManagedObject? {

    var entity = NSEntityDescription.entityForName(
        entity,
        inManagedObjectContext: self.managedContext
    )

    let object = NSManagedObject(
        entity: entity!,
        insertIntoManagedObjectContext: self.managedContext
    )

    for (key, attr) in attributes {
        object.setValue(attr, forKey: key)
    }

    var error: NSError?

    if !managedContext.save(&error) {
        return nil
    }

    return object
}

When you restart your app, pull the entity from CoreData:

func fetch(entity: String) -> [NSManagedObject]? {
    var request = NSFetchRequest(entityName: entity)
    var error: NSError?
    if let entities = managedContext.executeFetchRequest(
        request,
        error: &error
    ) as? [NSManagedObject] {

        if entities.count > 0 {
            return entities
        } 
    }

    return nil
}
kellanburket
  • 12,250
  • 3
  • 46
  • 73
  • If I then add this access token to my requests, how would my server verify the validity of said request? I want to make it so my user doesnt need to register. Kind of like it works with Tinder. – Filip ヅ Hájek Feb 26 '15 at 07:37
  • That seems more like a concern for your API and what security protocol you're looking to implement. have you investigated oauth? – kellanburket Feb 26 '15 at 08:16
  • I found this question http://stackoverflow.com/questions/4623974/design-for-facebook-authentication-in-an-ios-app-that-also-accesses-a-secured-we. I think it answered my question. Thank you for your help as it pointed me in the right direction. – Filip ヅ Hájek Feb 26 '15 at 09:15