SlideShare ist ein Scribd-Unternehmen logo
1 von 214
Downloaden Sie, um offline zu lesen
Get Ready
            1
An iOS Authentication
 Architecture for All
  How to stop reinventing the auth wheel




                                           2
René Cacheaux
Senior iOS Engineer
rene.cacheaux@mutualmobile.com




                                 3
There’s a

Pattern
  for That



              4
WHAT’S THE BIG DEAL?
                       5
Spend
    Time
Building
Features
     that
   ROCK
            6
Engineer
Amazing
First
Impressions

              7
Build
Reliable
    and
 Secure
   Apps
           8
Meet John

            9
10
image by adamjackson1984




                       11
image by Cbeck527




                    12
13
What to Build?
                 14
15
Business Cards




                 16
Ready, Set...
                17
18
19
but then...
          20
21
O...AUTH
           22
Really!?
           23
What exactly is
  OAuth?


                  24
WAIT!


I have to use a
UIWebView?!


                  25
Is there a library
    for this??


                     26
YES
GTMOAuth, whew.



                  27
Just
Download
   It!




           28
But then...



              29
Things start going
    wrong...




                     30
GTMOAuth
  1 or 2?


            31
Is Linked in OAuth
       1 or 2?


                     32
BOTH?



        33
One Hour Later



                 34
35
Jen!

       36
37
Jen went to
CocoaConf and...
                   38
Well...
There’s a Pattern


                    39
CocoaAuth

            40
AND there’s a reference
  implementation


                          41
Auth Kit

           42
Three Patterns
 Three Steps
                 43
Three Patters
Three Steps




   1            2          3
Accounts     Auth        Auth UI
           Controllers
                                   44
But first...
               45
John chose OAuth 2
   for Linked in


                     46
Why?
       47
John chose Google’s
    GTMOAuth


                      48
Why?
       49
Back to:
Three patterns
 Three steps


                 50
Three Patters
Three Steps




   1            2          3
Accounts     Auth        Auth UI
           Controllers
                                   51
So we want to
implement Accounts...

                        52
First
An Intro


           53
Meet OAuth 2.0




         OAuth 2



                   54
1st thing...



               55
image by tv




       The Access Token
                          56
It’s...



          57
Opaque
         58
It has...



            59
Scopes
         60
and it...



            61
Expires
          62
That’s OAuth 2
 Access Token

 On to Step 1,
  Accounts
                 63
1
Accounts



               64
If you need Auth
you have user’s...


                     65
And if you have
users, you need
   account
 management

                  66
Accounts makes up
 the model layer


                    67
3 Entities in
 Accounts
                68
1   Credentials


2   Accounts


3   Store


                  69
1   Credentials


2   Accounts


3   Store


                  70
AKOAuth2AccountCredential : NSObject

@property(nonatomic, copy) NSString *accessToken;
@property(nonatomic, strong) NSDate *expirationDate;




                                                       71
That’s all for
  credentials,
   super easy.


Accounts is next.
                    72
1   Credentials


2   Accounts


3   Store


                  73
AKAccount : NSObject

@property(nonatomic, copy, readonly) NSString *identifier;
@property(nonatomic, copy, readonly) NSString *username;
@property(nonatomic, copy, readonly) NSString *accountType;

- (void)clearCredential;




                                                              74
1   Account Type



2   Subclassing




                   75
Account Type
“com.linkedin”


                 76
Subclassing
AKAccount


              77
Class Structure
    Base



    Auth Protocol



    Library

                    78
AKAccount Base
@interface AKAccount ()
@property(nonatomic, copy, readwrite) NSString *identifier;

@end

@implementation AKAccount

+ (instancetype)accountWithIdentifier:(NSString *)identifier {
  return [[self alloc] initWithIdentifier:identifier];
}

- (id)initWithIdentifier:(NSString *)identifier {
  self = [super init];
  if (self) {
    _identifier = identifier;
  }
  return self;
}

- (void)clearCredential {
  // Abstract method.
}

@end




                                                                 79
AKOAuth2Account
@class AKOAuth2AccountCredential;

@interface AKOAuth2Account : AKAccount

@property(nonatomic, strong, readonly)
       AKOAuth2AccountCredential *OAuth2Credential;

@end

@implementation AKOAuth2Account

- (AKOAuth2AccountCredential *)OAuth2Credential {
  // Subclasses should implement this. They should always access
  // credentials from a secure store.
  return nil;
}

@end




                                                                   80
AKGTMOAuth2Account
@implementation AKGTMOAuth2Account

- (AKOAuth2AccountCredential *)OAuth2Credential {
  // Get credential from Google's GTMOAuth2 library.
}

- (void)clearCredential {
  // Remove credential from storage.
}

@end




                                                       81
AKAccount : NSObject

@property(nonatomic, copy, readonly) NSString *identifier;
@property(nonatomic, copy, readonly) NSString *username;
@property(nonatomic, copy, readonly) NSString *accountType;

- (void)clearCredential;




                                                              82
1   Credentials


2   Accounts


3   Store


                  83
AKAccountStore : NSObject

+ (void)registerAccountTypeClass:(Class)accountTypeClass;
+ (instancetype)sharedStore;
- (AKAccount *)newAccount;
- (void)saveAccount:(AKAccount *)account;
- (AKAccount *)authenticatedAccount;




                                                            84
Implementing

1   Account Ref Store



2   Credential Store



                        85
Implementing

1   Account Ref Store



2   Credential Store



                        86
Implementing

1   Account Ref Store



2   Credential Store



                        87
Credential Store

  1   Keychain




 2    Library Provided



                         88
1




    Keychain
               89
2

       Library
    Provided Store


                     90
GTMOAuth 2
- (AKOAuth2AccountCredential *)OAuth2Credential {

    AKGTMOAuth2AuthController *authController =
        [AKGTMOAuth2AuthController sharedController];
    GTMOAuth2Authentication *auth = [authController
                                     newGTMOAuth2Authentication];
    if (!auth) {
      return nil;
    }

    BOOL isAuthenticated =
        [GTMOAuth2ViewControllerTouch
            authorizeFromKeychainForName:authController.keychainItemName
                          authentication:auth];
    if (!isAuthenticated) {
      return nil;
    }

    AKOAuth2AccountCredential *credential =
        [[AKOAuth2AccountCredential alloc] init];
    credential.accessToken = auth.accessToken;
    return credential;
}




                                                                           91
AKAccountStore : NSObject

+ (void)registerAccountTypeClass:(Class)accountTypeClass;
+ (instancetype)sharedStore;
- (AKAccount *)newAccount;
- (void)saveAccount:(AKAccount *)account;
- (AKAccount *)authenticatedAccount;




                                                            92
Accounts, done.


Next pattern, #2

                   93
2
Auth Controller



                      94
Before looking at
Auth Controller...


                     95
More
OAuth2
 Fun




         96
The Actors
   Client



   Authorization Server



   Resource Server


                          97
The Client
   APP



             98
Authorization Server
                       99
Resource Server
                  100
Before you can
authenticate against
 an API’s OAuth you
     have to ...

                       101
Register the Client
                      102
Linked in
            103
And that gives you:



                      104
Client ID
            105
Client Secret
                106
That’s it. The Basics.



                         107
2
   Auth Controller



image by Damien Erambert
                               108
If you have auth...



                      109
You have a login...



                      110
If you have login,
UIKit has to launch
    a login flow.


                      111
Something has to
be in control, no?


                     112
2 Protocols
              113
<AKAuthControl>

- (void)beginAuthenticationAttempt;
- (void)unauthenticateAccount:(AKAccount *)account;




                     <AKAuthHandler>

- (void)presentAKLoginViewController:(UIViewController *)viewController;

- (void)authControllerAccount:(AKAccount *)account
              didAuthenticate:(id<AKAuthControl>)authController;

- (void)authControllerAccount:(AKAccount *)account
            didUnauthenticate:(id<AKAuthControl>)authController;




                                                                           114
Now the star of
   the show,
AKAuthController


                   115
AKAuthController : NSObject<AKAuthControl>


@property(nonatomic, weak) id<AKAuthHandler> authHandler;

+ (instancetype)sharedController;




                        it’s abstract
                                                            116
Simple



         117
How does it work?



                    118
1   The Flows


2   Linkedin Auth Controller


3   Calling Linkedin API


                           119
The Flows
            120
Login View Flow
id <AKAuthHandler>          AKAuthController            Login UIViewController



         beginAuthenticationAttempt



                                               initialize




        presentAKLoginViewController:




                                          user authenticated




     authControllerAccount:didAuthenticate:



                                                                                 121
Authenticated Flow
   id <AKAuthHandler>          AKAuthController




            beginAuthenticationAttempt




        authControllerAccount:didAuthenticate:




                                                  122
Bounce Back Flow
id <AKAuthHandler>          AKAuthController         Safari          App Delegate



         beginAuthenticationAttempt



                                          open URL


                                                              open URL




                                               user authenticated




     authControllerAccount:didAuthenticate:




                                                                                    123
So, the Linked in
Auth Controller


                    124
But first...



               125
Last OAuth 2 Lesson



                      126
Two Steps

1   The Grant



2   The Access Token (Part 2)




                                127
The Grant
            128
Yes, there IS
another token.


                 129
Auth Code
    Browser


    The Request


    The Redirect



                   130
Browser



          131
The Request



              132
Client                           Browser                       Auth Server




         Auth Code Request URL



                                           Auth Code GET Request



                                                 HTML Flow




                                     Redirect URL with Auth Code
    Redirect URL with Auth Code




                                                                             133
Query String
                  Params
https://www.linkedin.com/uas/oauth2/authorization

                                           ?response_type=code
                                           &client_id=YOUR_API_KEY
                                           &scope=SCOPE
                                           &state=STATE
                                           &redirect_uri=YOUR_REDIRECT_URI




                                                                             134
The Redirect



               135
Client                           Browser                       Auth Server




         Auth Code Request URL



                                           Auth Code GET Request



                                                 HTML Flow




                                     Redirect URL with Auth Code
    Redirect URL with Auth Code




                                                                             136
And now, get the
  Auth Code...


                   137
It’s in the redirect
 URL query string.


YOUR_REDIRECT_URI/?code=AUTHORIZATION_CODE




                                             138
So that’s the Auth
   Code Grant


                     139
Now, it’s time for
some more Access
   Token fun.


                     140
The Access Token
                   141
Now that I have an
  Auth Code...


                     142
How do I get an
Access Token?


                  143
Request



Response




           144
Request



          145
Client                              Auth Server




  Access Token POST Request with Auth Code




          JSON with Access Token




                                                  146
Query String
                  Params
https://www.linkedin.com/uas/oauth2/accessToken

                                           ?grant_type=authorization_code
                                           &code=AUTHORIZATION_CODE
                                           &redirect_uri=YOUR_REDIRECT_URI
                                           &client_id=YOUR_API_KEY
                                           &client_secret=YOUR_SECRET_KEY




                                                                             147
Response



           148
Client                              Auth Server




  Access Token POST Request with Auth Code




          JSON with Access Token




                                                  149
Payload

{
    "expires_in":5184000,
    "access_token":"AQXdSP_W41_UPs5ioT_t8HESyODB4FqbkJ8LrV_5mf
                    f4gPODzOYR"
}




                                                                 150
So that’s how you
get an Access Token


                      151
Back to... Linked in
 Auth Controller


                       152
Subclass Structure

 AKAuthController
       Base



 AKGTMOAuth2AuthController
      Auth Protocol



 MALinkedInAuthController
       Library

                             153
Using GTMOAuth2



                  154
Code Demo



            155
We now have an
Access token in the
    Keychain


                      156
Time to make some
     API Calls


                    157
Calling the
Linked in API


                158
1
    Getting Access Token from
    Account Store


2   Using the Access Token


3   Handling Bad Token Responses



                                   159
1

      Getting
    Access Token


                   160
2

Using Access Token



                     161
Client                             Resource Server




         API Request with Access Token




             Protected Resource




                                                     162
Code Demo



            163
FINALLY! API Calls



                     164
3




    Bad Token
                165
Get Auth Controller



                      166
AKAuthController                   Client                           Resource Server




                                            API Request with Access Token




                                                     Bad Token




          Unauthenticate Account




                                                                                      167
Log Out Account
                  168
And... Wait How
will the app react?


                      169
That’s where Auth
  UI comes in.


                    170
3
Auth UI



              171
Container View
  Controller
                 172
Application Container View Controller


Unauthenticated View        Authenticated View
     Controller                 Controller




                                                 173
1   Children View Controllers


2   Installation


3   Flows


                            174
Children



           175
Installation



               176
Code Demo



            177
Flows



        178
Log In



         179
Child Controller                Container                Auth Controller




         beginAuthenticationAttempt



                                      beginAuthenticationAttempt




                                  authControllerAccount:didAuthenticate:




 transition into authenticated view controller




                                                                           180
Log Out



          181
Child Controller                Container                Auth Controller




                                 authControllerAccount:didUnauthenticate:




 transition into unauthenticated view controller




                                                                            182
That’s AuthUI



                183
Whew!
Those are the
  Patterns


                184
Back in SFO...



                 185
image by adamjackson1984




                       186
187
And the winner is...



                       188
189
190
10 years later...



                    191
192
John opens a
hookah bar...


                193
YES...
a hookah bar




               194
and



      195
JUST
MARRIED!
           196
The End



          197
So what’s the point?



                       198
Auth Sucks



             199
Auth Takes Time



                  200
It gets in the way



                     201
Don’t spend

TIME
 on auth



              202
Spend time on

Features
                 203
Benefits



           204
Save Time
   and
  Effort


            205
Consistent
 Interface


             206
It’s simple



              207
Future



         208
Future of iOS



                209
Future of
CocoaAuth
    &
 Auth Kit

             210
Resources




            211
/RCacheaux/AuthKit




                     212
René Cacheaux
Senior iOS Engineer
rene.cacheaux@mutualmobile.com

@RCachATX
rene.cacheaux@gmail.com




                                 213
214

Weitere ähnliche Inhalte

Ähnlich wie An iOS Authentication Architecture for All

Local Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothLocal Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothCocoaHeads France
 
HashiCorp Vault Workshop:幫 Credentials 找個窩
HashiCorp Vault Workshop:幫 Credentials 找個窩HashiCorp Vault Workshop:幫 Credentials 找個窩
HashiCorp Vault Workshop:幫 Credentials 找個窩smalltown
 
Authentication in microservice systems - fsto 2017
Authentication in microservice systems - fsto 2017Authentication in microservice systems - fsto 2017
Authentication in microservice systems - fsto 2017Dejan Glozic
 
Wce internals rooted_con2011_ampliasecurity
Wce internals rooted_con2011_ampliasecurityWce internals rooted_con2011_ampliasecurity
Wce internals rooted_con2011_ampliasecurityfangjiafu
 
Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]RootedCON
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with MockitoAlexander De Leon
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
Tucson Blockchain Developers Meetup #1 - Cryptokitties by Destry
Tucson Blockchain Developers Meetup #1 - Cryptokitties by DestryTucson Blockchain Developers Meetup #1 - Cryptokitties by Destry
Tucson Blockchain Developers Meetup #1 - Cryptokitties by DestryDestry Saul
 
ZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningMikhail Sosonkin
 
Zeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningZeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningSynack
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncmdevtalk
 
Rodauth: Clean Authentication
Rodauth: Clean AuthenticationRodauth: Clean Authentication
Rodauth: Clean AuthenticationValikos Ostakh
 
Rodauth: Clean Authentication - Valentine Ostakh
Rodauth: Clean Authentication - Valentine OstakhRodauth: Clean Authentication - Valentine Ostakh
Rodauth: Clean Authentication - Valentine OstakhRuby Meditation
 
Tutorial s crypto api session keys
Tutorial   s crypto api session keysTutorial   s crypto api session keys
Tutorial s crypto api session keysDr. Edwin Hernandez
 

Ähnlich wie An iOS Authentication Architecture for All (20)

Local Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothLocal Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban Toth
 
HashiCorp Vault Workshop:幫 Credentials 找個窩
HashiCorp Vault Workshop:幫 Credentials 找個窩HashiCorp Vault Workshop:幫 Credentials 找個窩
HashiCorp Vault Workshop:幫 Credentials 找個窩
 
Authentication in microservice systems - fsto 2017
Authentication in microservice systems - fsto 2017Authentication in microservice systems - fsto 2017
Authentication in microservice systems - fsto 2017
 
Wce internals rooted_con2011_ampliasecurity
Wce internals rooted_con2011_ampliasecurityWce internals rooted_con2011_ampliasecurity
Wce internals rooted_con2011_ampliasecurity
 
Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
Tucson Blockchain Developers Meetup #1 - Cryptokitties by Destry
Tucson Blockchain Developers Meetup #1 - Cryptokitties by DestryTucson Blockchain Developers Meetup #1 - Cryptokitties by Destry
Tucson Blockchain Developers Meetup #1 - Cryptokitties by Destry
 
ZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanning
 
Zeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningZeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanning
 
Esquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdMEsquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdM
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & sync
 
Rodauth: Clean Authentication
Rodauth: Clean AuthenticationRodauth: Clean Authentication
Rodauth: Clean Authentication
 
Rodauth: Clean Authentication - Valentine Ostakh
Rodauth: Clean Authentication - Valentine OstakhRodauth: Clean Authentication - Valentine Ostakh
Rodauth: Clean Authentication - Valentine Ostakh
 
Checking Bitcoin
 Checking Bitcoin Checking Bitcoin
Checking Bitcoin
 
Tutorial s crypto api session keys
Tutorial   s crypto api session keysTutorial   s crypto api session keys
Tutorial s crypto api session keys
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 

Mehr von René Cacheaux

Writing Code for Humans, not Computers
Writing Code for Humans, not ComputersWriting Code for Humans, not Computers
Writing Code for Humans, not ComputersRené Cacheaux
 
Bringing Swift into your Objective-C Projects
Bringing Swift into your Objective-C ProjectsBringing Swift into your Objective-C Projects
Bringing Swift into your Objective-C ProjectsRené Cacheaux
 
Modular View Controller Hierarchies
Modular View Controller HierarchiesModular View Controller Hierarchies
Modular View Controller HierarchiesRené Cacheaux
 
Capturing Users' Hearts
Capturing Users' HeartsCapturing Users' Hearts
Capturing Users' HeartsRené Cacheaux
 
How to Stop Reinventing the Auth Wheel
How to Stop Reinventing the Auth WheelHow to Stop Reinventing the Auth Wheel
How to Stop Reinventing the Auth WheelRené Cacheaux
 
iOS Combining Touch and Animation
iOS Combining Touch and AnimationiOS Combining Touch and Animation
iOS Combining Touch and AnimationRené Cacheaux
 

Mehr von René Cacheaux (6)

Writing Code for Humans, not Computers
Writing Code for Humans, not ComputersWriting Code for Humans, not Computers
Writing Code for Humans, not Computers
 
Bringing Swift into your Objective-C Projects
Bringing Swift into your Objective-C ProjectsBringing Swift into your Objective-C Projects
Bringing Swift into your Objective-C Projects
 
Modular View Controller Hierarchies
Modular View Controller HierarchiesModular View Controller Hierarchies
Modular View Controller Hierarchies
 
Capturing Users' Hearts
Capturing Users' HeartsCapturing Users' Hearts
Capturing Users' Hearts
 
How to Stop Reinventing the Auth Wheel
How to Stop Reinventing the Auth WheelHow to Stop Reinventing the Auth Wheel
How to Stop Reinventing the Auth Wheel
 
iOS Combining Touch and Animation
iOS Combining Touch and AnimationiOS Combining Touch and Animation
iOS Combining Touch and Animation
 

An iOS Authentication Architecture for All