Рубрики
Без рубрики

Войдите В Систему С Amazon, используя AWS Amplify Auth

В этом руководстве вы узнаете, как использовать службу аутентификации AWS Amplify для включения входа в систему с помощью Amazon… С тегами android, java, aws, codenewbie.

В этом руководстве вы узнаете, как использовать службу аутентификации AWS Amplify для включения входа в Amazon в приложении для Android. Интерфейс приложения будет выглядеть следующим образом

  • Создайте новый проект Android Studio, используя пустой шаблон Activity
  • Мы собираемся использовать мое приложение авторизации для поля имени
  • Обновить build.gradle (Проект: Мое приложение для авторизации) как показано ниже
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        // ******* Add this line *******
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // ******* Add this line *******
        mavenCentral()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
  • Обновите build.gradle (Модуль:приложение), как показано ниже
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.offlineprogrammer.myauthapplication"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // ******* Add these lines *******
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    // ******* Add these lines *******
    implementation 'com.amplifyframework:core:1.1.1'
    implementation 'com.amplifyframework:aws-auth-cognito:1.1.1'

}
  • Обязательно запустите Gradle Sync
  • Выполните приведенную ниже команду в терминале Android Studio
amplify init
  • Вам будет предложено ввести несколько подробностей, как показано ниже
? Enter a name for the project MyAuthApplication
? Enter a name for the environment amplify
? Choose your default editor: None
? Choose the type of app that you're building android
Please tell us about your project
? Where is your Res directory:  app/src/main/res
Using default provider  awscloudformation

For more information on AWS Profiles, see:


? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use default
Adding backend environment amplify to AWS Amplify Console app: d2yvhmdiprhhlh

  • После завершения вы получите подтверждение ниже
Your project has been successfully initialized and connected to the cloud!
  • Создайте новый класс и назовите его My Auth Application
  • Мы будем использовать этот класс для инициализации Amplify, как показано ниже – обратите внимание, как класс расширяется из приложения
public class MyAuthApplication  extends Application {
    private static final String TAG = "MyAuthApplication";

    @Override
    public void onCreate() {
        super.onCreate();

        try {
            Amplify.addPlugin(new AWSCognitoAuthPlugin());

            Amplify.configure(getApplicationContext());

            Log.i(TAG, "Initialized Amplify");
        } catch (AmplifyException error) {
            Log.e(TAG, "Could not initialize Amplify", error);
        }

    }
}
  • Обновление AndroidManifest.xml чтобы добавить атрибут android:name со значением .Мое приложение для авторизации как показано ниже



    
  • Войдите здесь используя свою учетную запись разработчика Amazon для создания профиля безопасности
  • Введите имя профиля безопасности, Описание профиля безопасности и URL-адрес Уведомления о конфиденциальности согласия, затем нажмите Сохранить
  • Обратите внимание на идентификатор клиента и секрет клиента
  • Выполните приведенную ниже команду, чтобы настроить категорию авторизации
amplify add auth
  • При появлении запроса укажите сведения ниже
Do you want to use the default authentication and security configuration? Default configuration with Social Provider (Federation)
 Warning: you will not be able to edit these selections. 
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
 What domain name prefix do you want to use? myauthapplication7ae1f03e-7ae1f03e
 Enter your redirect signin URI: myauthapp://callback/
? Do you want to add another redirect signin URI No
 Enter your redirect signout URI: myauthapp://signout/
? Do you want to add another redirect signout URI No
 Select the social providers you want to configure for your user pool: Login With Amazon
  
 You've opted to allow users to authenticate via Amazon.  If you haven't already, you'll need to create an Amazon App ID. 
 
 Enter your Amazon App ID for your OAuth flow:  amzn1.application-oa2-client.88a2ae52a05349d8a8027c93d9e5fc51
 Enter your Amazon App Secret for your OAuth flow:  b9f0fa476eea36200d8f1f304adc7711a63fa6422d22d515b50f729f33560a61
Successfully added resource myauthapplication7ae1f03e locally

  • Опубликуйте эти изменения, выполнив приведенную ниже команду
amplify push
  • После завершения он отобразит URL-адрес конечной точки вашего пользовательского интерфейса, как показано ниже
✔ All resources are updated in the cloud

Hosted UI Endpoint: 
Test Your Hosted UI Endpoint: 
  • На портале разработчика Amazon нажмите на профиль безопасности, который вы создали выше, и выберите вкладку веб-настройки
  • Выберите Редактировать, затем введите URL-адрес конечной точки пользовательского интерфейса в поле Разрешенные исходные данные и введите URL-адрес конечной точки пользовательского интерфейса с конечной точкой ответа/oauth2/idp в поле Разрешенные возвращаемые URL-адреса.
  • Обновите AndroidManifest.xm, чтобы установить android:launchMode и intent-filter для основного действия, как показано ниже

            
                
                
                
                
                
                
            
        
  • Чтобы получить ответ от веб-интерфейса входа в систему, добавьте приведенный ниже метод в MainActivity
@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getData() != null && "myauthapp".equals(intent.getData().getScheme())) {
            Amplify.Auth.handleWebUISignInResponse(intent);
        }
    }
  • Загрузите кнопку входа в систему с здесь и добавьте ее в свою папку для рисования. мы собираемся использовать оба (btnlwa_gold_login.png) и (btnlwa_gold_login_pressed.png).
  • Щелкните правой кнопкой мыши на папке с возможностью рисования и создайте файл ресурсов с возможностью рисования. Назовите это login_button_image_state.xml
  • Этот файл определит селектор для кнопки входа в систему, как показано ниже

    
    
  • Обновите activity_main.xml чтобы добавить кнопку входа в систему и индикатор выполнения, как показано ниже



    


    

    

        
    


  • Обновите MainActivity.java ввести метод входа в систему, который будет вызываться, когда пользователь нажимает на кнопку входа. ниже приведен окончательный код MainActivity.java
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    ImageButton login_with_amazon;
    TextView login_textView;
    ProgressBar log_in_progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login_with_amazon = findViewById(R.id.login_with_amazon);
        login_textView = findViewById(R.id.login_textView);
        log_in_progress = findViewById(R.id.log_in_progress);

        login_with_amazon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                log_in_progress.setVisibility(View.VISIBLE);
                login_with_amazon.setVisibility(View.GONE);
                login();
            }
        });


    }

    private void login() {
        Amplify.Auth.signInWithSocialWebUI(
                AuthProvider.amazon(),
                this,
                result -> {
                    Log.i(TAG, "AuthQuickstart RESULT " + result.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            login_textView.setText("Login is successfull");
                            login_with_amazon.setVisibility(View.GONE);
                            log_in_progress.setVisibility(View.GONE);
                        }
                    });
                },
                error -> {
                    Log.e(TAG, "AuthQuickstart ERROR " + error.toString());
                }
        );

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getData() != null && "myauthapp".equals(intent.getData().getScheme())) {
            Amplify.Auth.handleWebUISignInResponse(intent);
        }
    }

}

Проверьте полный код на github и следуйте за мной на Twitter для получения дополнительных советов о #кодировании, # обучении, #технологиях, #Java, # JavaScript, #Аутизме, #воспитании детей … и т.д.

Проверьте мои приложения в Google Play

Оригинал: “https://dev.to/offlineprogrammer/login-with-amazon-using-aws-amplify-auth-3bmh”