Android – how do i make a login with basic auth in kotlin with a get requet api? – stack overflow

Manually adding services configuration file

This can be achieved by downloading the google-services.json file, then pasting it into the Android project root and adding the necessary dependencies manually.

This process requires you to have a running app so that it sends a signal to firebase servers. This indicates that the project configuration file and dependencies are working as expected. This is noticeably not the best option as it is more complicated compared to method 2.

Through Android studio Firebase assistant

This is a less complicated and more straightforward method that does most of the work for you. For the sake of simplicity, we’ll use this method.

Launch Firebase assistant by heading to Tools » firebase

“Launch Firebase assistant”

“Connect to Firebase”

Click Authentication » Email and password authentication

“Connect to Firebase”

Click Connect to Firebase. You’ll be taken to the Firebase website and prompted to choose a project to connect with.

Choose the Firebase-auth we just created. By so doing, the google-services.json file is automatically downloaded into your project.

Click Connect and you’ll see a message like the one below.

Go back to Android studio to finish up the setup.

“Accept changes”

C) create account activity

SignInactivity is similar to CreateAccountActivity. The only difference is that we’ll use the Firebase signInWithEmailAndPassword() function. Inputs are processed the same way as when creating an account.

Here is the code for that:

Explanation

Each directory plays an important role in the app’s design.

How do i make a login with basic auth in kotlin with a get requet api?

I’m trying to make a Login screen I’ve made in Android Studio to work with Kotlin but I’m having troubles making a class that will “attach” the Basic Authentication to all the requests. To do this I am using Retrofit2 and OkHttp3.

These are the relevant classes in my code:

GET_LOGIN.kt

package com.joaomartins.srodkitrwale

import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Headers

interface GET_LOGIN {
    @GET("login")
    fun getAccessToken() : Call<String>
}

RetrofitClient.kt

package com.joaomartins.srodkitrwale

import android.app.Application
import android.util.Base64
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Interceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor

    val username = Login().userTxt.text
    val password = Login().passTxt.text
    val credentials = username   ":"   password
    val AUTH = "Basic "   Base64.encodeToString(credentials.toByteArray(Charsets.UTF_8), Base64.DEFAULT).replace("n", "")

    val retrofit = RetrofitClient().init()
            //.getBytes(), Base64.DEFAULT).replace("n", "")
//val AUTH2 = java.util.Base64.getEncoder().encode((username   ":"   password).toByteArray()).toString(Charsets.UTF_8)

class RetrofitClient {
    // Initializing Retrofit
    fun init() : Retrofit{

        // Creating the instance of an Interceptor
        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY


        // Creating the OkHttp Builder
        val client = OkHttpClient().newBuilder()


        // Creating the custom Interceptor with Headers
        val interceptor = Interceptor { chain ->
            val request = chain?.request()?.newBuilder()?.addHeader("Authorization", AUTH)?.build()
            chain?.proceed(request)
        }
        client.addInterceptor(interceptor) // Attaching the Interceptor

        // Creating the instance of a Builder
        return Retrofit.Builder()
                .baseUrl("https://srodki.herokuapp.com/")   // The API server
                .client(client.build())                                     // Adding Http Client
                .addConverterFactory(GsonConverterFactory.create()) // Object Converter
                .build()
    }

    fun providesGetLogin(): GET_LOGIN = retrofit.create(GET_LOGIN::class.java)
}

Login.kt

package com.joaomartins.srodkitrwale

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.util.Base64
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit

class Login : AppCompatActivity() {

    val apiLogin = RetrofitClient().providesGetLogin().getAccessToken()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        loginBtn.setOnClickListener {
            val user = userTxt.text
            val pass = passTxt.text

            if (validateLogin(user, pass)){
                login(user, pass)
            }
        }
    }

    fun validateLogin(user: Editable, pass: Editable): Boolean {
        if (user == null || user.trim().isEmpty()){
            Toast.makeText(this, "Missing Username or Password", Toast.LENGTH_SHORT).show()
            return false
        }
        if (pass == null || pass.trim().isEmpty()){
            Toast.makeText(this, "Missing Username or Password", Toast.LENGTH_SHORT).show()
            return false
        }
        return true
    }

    fun login(user: Editable, pass: Editable) {
        /*val intent = Intent(this, List_users::class.java)
        startActivity(intent)*/
        apiLogin.enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                Log.d("check", "Reached this place")
                if(!response.isSuccessful)
                    Log.d("failed", "No Success")
                Toast.makeText(this@Login, "Login Successful!", Toast.LENGTH_SHORT).show()
                val intent = Intent(this@Login, List_users::class.java)
                startActivity(intent)
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Toast.makeText(this@Login, "Login Failed.", Toast.LENGTH_SHORT).show()
            }
        })

    }

}

The class that would be responsible for the creation of the request with the encrypted authentication is the RetrofitClient class.

I believe the error lies within the following lines of code:

val username = Login().userTxt.text
val password = Login().passTxt.text
val credentials = username   ":"   password
val AUTH = "Basic "   Base64.encodeToString(credentials.toByteArray(Charsets.UTF_8), Base64.DEFAULT).replace("n", "")

There should be an easier way to do this but I am still learning Android and Kotlin.

Key points

  • margin: This is the field around a view that serves as its part. Think of it as the area surrounding a view. It’s always given in density pixels (DP).

  • Padding: This is the area inside the view that defines how far from the edges is whatever is inside the view.

Setting layout_width = “0dp” in constraint layout means that the view together with its margin will occupy the whole horizontal constraint set. This works best if the view below is constrained horizontally to the one above it.

Copy the code below and paste it to activity_sign_in.xml.

Kotlin

One more thing concerning firebase

Since we want to use email and password authentication, we have to enable it in our project’s console. To do that navigate to Authentication > sign-in method then enable email and password authentication. It should look like this.

“Enable auth”

“Enabled auth”

Congratulations! We have finished setting up Firebase authentication.

Prerequisites

To follow through this tutorial you’re required to have:

Step 1 – creating an android project

First, we need to create an Android project that we will use in the entire tutorial. To do this, launch Android studio and create an Empty Activity project with the following configurations

  • Name as Firebase auth.
  • Package name as com.<your_name>.firebaseauth (without spaces).
  • Language select Kotlin.
  • Minimum SDKselect API 21: Android 5.0 (Lollipop) and finally.
  • don’t check use legacy android support libraries as doing so will limit us from using some android libraries.

Step 2 – sign in to android studio

You need to sign in to Android studio in order to use services such as Firebase. This is where the Google account comes in.
To sign in, click the icon at the top right corner.

“Android studio sign in step 1”

By clicking Sign in a browser window pops up and prompts you to select an account or create one for Android studio.

“Android studio sign in choose account”

A bunch of permissions are required for you to sign in.

“Android studio sign in permissions”

Allow the permissions to successfully sign in to Android studio. You can now access Firebase and Google cloud platform services via Android studio.

In our case, we only need Firebase.

“Android studio sign in success”

Go back to Android studio and you’ll see your email in the account section.

Step 3 – creating a firebase project

We need a Firebase project that we’ll eventually connect with our Android app. This project will give us access to most of the Firebase services, not limited to authentication and analytics.

This process involves several stages.

“Create Firebase project”

  • To create a new project click Add project. This involves three steps.

“Create Firebase project”

“Create Firebase project”

We start by giving a name to the project. Let’s name it Firebase-auth. The project name shouldn’t have spaces, instead, use a hyphen.

Just below the name, is a unique ID used to identify your project among the millions of Firebase projects out there. Click the continue button.

“Create Firebase project step 2 of 3”

  • Since we’re going to use Google analytics in our app, ensure that the analytics switch is checked. Hit continue to proceed.

Wait for project creation to finish up.

“Create Firebase finish up 3 0f 3”

Now our project is ready to be connected to our app.

Step 4 – connecting firebase project to an android app

There are two ways to connect a Firebase project to an Android app.

Conclusion

In this article, we’ve learned some of the best that Firebase has to offer and particularly authentication. The project we created can be improved further for production apps and it’ll still work fine. I can’t wait to see what you’ll build with Firebase authentication.

Похожее:  Личный кабинет Томтел, регистрация и состояние счета

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *