Formation PUB900 : Développer une application pour iPhone avec SwiftUI, H-2024 L'authentification

58.1 Face ID


À la base, on sait que l'usager est authentifié sur son appareil mobile s'il peut accéder aux applications. Cependant, certaines applications qui manipulent des informations sensibles peuvent augmenter la sécurité en demandant une nouvelle authentification lors de leur ouverture.

La fonctionnalité Face ID est disponible pour déverrouiller l'appareil depuis iPhone X et iPad 2018.

Si Face ID n'est pas disponible ou s'il a été désactivé, le code que je vous propose demandera à l'usager d'entrer le mot de passe de son téléphone.

Pour que votre application demande une authentifiation lors de son ouverture, suivez ces étapes :

  • Pour pouvoir travailler avec la classe LAContext, qui permet d'utiliser l'authentification par données biométriques, vous devez ajouter la clé NSFaceIDUsageDescription dans Info.plist. Cette clé correspond au nom « Privacy - Face ID Usage Description ».

    J'aime lui donner la valeur « $(PRODUCT_NAME) a besoin d'utiliser Face ID pour valider votre identité. » ou encore « Vous devez vous authentifier pour accéder à cette application. ».

    Privacy - Face ID Usage Description

    Une fois que l'authentification sera codée, la valeur que vous donnez à la clé NSFaceIDUsageDescription apparaîtra sous le message « Souhaitez-vous autoriser " Mon Projet " à utiliser Face ID? » la première fois que l'application sera lancée sur le iPhone.

    Souhaitez-vous autoriser « Mon Projet » à utiliser Face ID? Mon Projet a beson d'utiliser Face ID pour valider votre identité.

  • Afin de maximiser la réutilisation du code entre applications, je vous conseille de placer le code d'authentification dans sa propre classe. Les changements seront transmis à la vue principale grâce au mécanisme d'observation.
    Fichier Authentification.swift (SwiftUI)

    import Foundation
    import LocalAuthentication

    enum Statut {
      case authentifie, nonAuthentifie
    }

    @Observable
    class Authentification {
      var statut: Statut = .nonAuthentifie
      var demandeFaite: Bool = false   // permet au programme de réagir différemment avant que authentifier() ait été appelée
      let context = LAContext()
      var error: NSError?

      func authentifier() {
        // Avec .deviceOwnerAuthentication (plutôt que .deviceOwnerAuthenticationWithBiometrics), demandera une authentification par code si Face ID n'est pas disponible.
        if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
          
          let justificationSiFaceIDNonDisponible = "Vous devez vous authentifier pour accéder à cette application."

          context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: justificationSiFaceIDNonDisponible ) { success, error in

            if success {
              // Retourne au fil d'exécution principal
              DispatchQueue.main.async {
                self.statut = .authentifie
                self.demandeFaite = true
              }
            } else {
              print(error?.localizedDescription ?? "L'authentification a échoué.")
              DispatchQueue.main.async {
                self.demandeFaite = true
              }
            }
          }
        }
      }
    }

  • Dans ContentView, instanciez un objet Authentification. Dans le onAppear(), appelez la méthode authentifier(). Affichez les détails sensibles de la vue seulement si l'authentification a eu lieu.
    Fichier ContentView.swift (SwiftUI)

    struct ContentView: View {
      @State private var authentification: Authentification = Authentification()
      ...

      var body: some View {
        NavigationStack {
          VStack {
            if authentification.statut == .nonAuthentifie {
              if !authentification.demandeFaite {
                ProgressView()
              }
              else {
                // arrivera ici si l'usager clique sur Annuler sur l'écran Face ID ou sur l'écran de saisie de son code
                Text("Vous devez être authentifié pour accéder à cette application.")
                  .padding()
              }
            }
            else {
              ...
            }
          }
          .onAppear(perform: {
            // ne refera pas l'authentification si on passe à une autre vue puis qu'on revient à celle-ci
            if authentification.statut == .nonAuthentifie {
              authentification.authentifier()
            }
          })
        }
      }
    }

  • Au lancement de votre application sur un iPhone, l'usager verra l'animation de Face ID pendant que l'authentification a lieu.

    Face IDFace IDFace ID

  • Dans le cas où Face ID ne fonctionne pas, l'usager sera invité à entrer son code d'authentification avec, en plus du message standard, la justification que vous avez passée en paramètre lors de l'appel à context.evaluatePolicy().

    Entrez le code de l'iPhone pour « Mon Projet ». Vous devez vous authentifier pour accéder à cette application.

▼Publicité

Veuillez noter que le contenu de cette fiche vous est partagé à titre gracieux, au meilleur de mes connaissances et sans aucune garantie.
Merci de partager !
Soumettre