Ricerca…


Parametri

Colonna Colonna
Cellula Cellula

Osservazioni

Innanzitutto, stabilire se il dispositivo è in grado di accettare l'input Touch ID.

if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))

Se lo fa, possiamo visualizzare l'interfaccia utente Touch ID utilizzando:

context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);

Ci sono tre informazioni che dobbiamo passare in EvaluatePolicy : la politica stessa, una stringa che spiega perché l'autenticazione è necessaria e un gestore di risposte. Il gestore di risposta comunica all'applicazione cosa deve fare in caso di autenticazione riuscita o non riuscita.

Uno degli avvertimenti di Local Authentication è che deve essere eseguito in primo piano, quindi assicurati di utilizzare InvokeOnMainThread per il gestore di risposta:

var replyHandler = new LAContextReplyHandler((success, error) =>
    {

        this.InvokeOnMainThread(() =>
        {
            if (success)
            {
                Console.WriteLine("You logged in!");
                PerformSegue("AuthenticationSegue", this);
            }
            else {
                //Show fallback mechanism here
            }
        });

    });

Per determinare se il database delle impronte digitali autorizzate è stato modificato, è possibile controllare la struttura opaca (NSData) restituita dal context.EvaluatedPolicyDomainState . L'app dovrà memorizzare e confrontare lo stato della politica per rilevare le modifiche. Una cosa da notare quale Apple afferma:

Tuttavia, la natura del cambiamento non può essere determinata da questi dati.

if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
{
    var policyState = context.EvaluatedPolicyDomainState;

    var replyHandler = new LAContextReplyHandler((success, error) =>
    {

        this.InvokeOnMainThread(() =>
        {
            if (success)
            {
                Console.WriteLine("You logged in!");
                PerformSegue("AuthenticationSegue", this);
            }
            else {
                //Show fallback mechanism here
            }
        });

    });
    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
};

Aggiungi Touch ID alla tua app

Innanzitutto, stabilire se il dispositivo è in grado di accettare l'input Touch ID.

if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))

Se lo fa, possiamo visualizzare l'interfaccia utente Touch ID utilizzando:

context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);

Ci sono tre informazioni che dobbiamo passare in EvaluatePolicy : la politica stessa, una stringa che spiega perché l'autenticazione è necessaria e un gestore di risposte. Il gestore di risposta comunica all'applicazione cosa deve fare in caso di autenticazione riuscita o non riuscita.

Uno degli avvertimenti di Local Authentication è che deve essere eseguito in primo piano, quindi assicurati di utilizzare InvokeOnMainThread per il gestore di risposta:

var replyHandler = new LAContextReplyHandler((success, error) =>
{
    this.InvokeOnMainThread(() =>
    {
        if (success)
        {
            Console.WriteLine("You logged in!");
            PerformSegue("AuthenticationSegue", this);
        }
        else {
            //Show fallback mechanism here
        }
    });
});

Per determinare se il database delle impronte digitali autorizzate è stato modificato, è possibile controllare la struttura opaca (NSData) restituita dal context.EvaluatedPolicyDomainState . L'app dovrà memorizzare e confrontare lo stato della politica per rilevare le modifiche. Una cosa da notare quale Apple afferma:

Tuttavia, la natura del cambiamento non può essere determinata da questi dati.

if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError))
{
    var policyState = context.EvaluatedPolicyDomainState;

    var replyHandler = new LAContextReplyHandler((success, error) =>
    {

        this.InvokeOnMainThread(() =>
        {
            if (success)
            {
                Console.WriteLine("You logged in!");
                PerformSegue("AuthenticationSegue", this);
            }
            else {
                //Show fallback mechanism here
            }
        });

    });
    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);
};

Esempio di pulsante

partial void AuthenticateMe(UIButton sender)
{
    var context = new LAContext();
    //Describes an authentication context 
    //that allows apps to request user authentication using Touch ID.
    NSError AuthError;
    //create the reference for error should it occur during the authentication.
    var myReason = new NSString("To add a new chore");
    //this is the string displayed at the window for touch id

    if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) 
    // check if the device have touchId capabilities.
    {
        var replyHandler = new LAContextReplyHandler((success, error) =>
        {

            this.InvokeOnMainThread(() =>
            {
                if (success)
                {
                    Console.WriteLine("You logged in!");
                    PerformSegue("AuthenticationSegue", this);
                }
                else {
                    //Show fallback mechanism here
                }
            });

        });
        context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, myReason, replyHandler);//send touch id request
    };
}

Usando il portachiavi

Fonte di lavoro: https://github.com/benhysell/V.TouchIdExample

Descrizione estesa del modulo - http://benjaminhysell.com/archive/2014/11/authentication-in-xamarin-ios-with-touch-id-or-passcode/

//Simple View with a switch to enable / disable Touch ID and 
//a button to invoke authentication 

/// <summary>
/// Enable/Disable Touch ID
/// </summary>
/// <param name="sender">Sender.</param>
partial void TouchIdEnableDisable(UISwitch sender)
{
    if (sender.On)
    {
        //enable Touch ID          
        //set our record
        //note what you fill in here doesn't matter, just needs to be 
        //consistent across all uses of the record
        var secRecord = new SecRecord(SecKind.GenericPassword)
        {
            Label = "Keychain Item",
            Description = "fake item for keychain access",
            Account = "Account",
            Service = "com.yourcompany.touchIdExample",
            Comment = "Your comment here",
            ValueData = NSData.FromString("my-secret-password"),
            Generic = NSData.FromString("foo")
        };

        secRecord.AccessControl = new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly, SecAccessControlCreateFlags.UserPresence);
        SecKeyChain.Add(secRecord);
                                
        authenticateButton.Enabled = true;
    }
    else
    {
        //disable Touch ID
        var record = new SecRecord(SecKind.GenericPassword)
        {
            Service = "com.yourcompany.touchIdExample",
            UseOperationPrompt = "Authenticate to Remove Touch ID / Passcode from Test App"
        };

        SecStatusCode result;

        //query one last time to ensure they can remove it
        SecKeyChain.QueryAsRecord(record, out result);
        if (SecStatusCode.Success == result || SecStatusCode.ItemNotFound == result)
        {
            //remove the record
            SecKeyChain.Remove(record);
            authenticateButton.Enabled = false;
        }
        else
        {
            //could not authenticate, leave switch on
            sender.On = true;
         }                
    }
}

/// <summary>
/// Show Touch ID to user and evaluate authentication
/// </summary>
/// <param name="sender">Sender.</param>
partial void AuthenticateUser(UIButton sender)
{
    var rec = new SecRecord(SecKind.GenericPassword)
    {
        Service = "com.yourcompany.touchIdExample",
        UseOperationPrompt = "Authenticate to access Test App"
    };
    SecStatusCode res;
    SecKeyChain.QueryAsRecord(rec, out res);
    if (SecStatusCode.Success == res || SecStatusCode.ItemNotFound == res)
    {
        //Success!!  
        //add your code here to continue into your application
        AuthenticatedLabel.Hidden = false;
    }
    else
    {
        //Failure
        AuthenticatedLabel.Hidden = true;
    }
}


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow