@kabuka321

Как сохранить JWT токен для последующих запросов на сервер?

При авторизации на сервере выдается JWT токен. В другом активити нужно вызвать Post запрос с использованием этого токена. Как реализовать его сохранение в клиенте.
MainActivity.java
package com.example.clientapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.clientapp.Model.Response;
import com.example.clientapp.Model.Token;
import com.example.clientapp.retrofit.RetrofitService;
import com.example.clientapp.retrofit.UserApi;
import retrofit2.Call;
import retrofit2.Callback;

public class MainActivity extends AppCompatActivity  {
    SharedPreferences prefs;
    RetrofitService retrofitService = new RetrofitService();
    UserApi userApi = retrofitService.getRetrofit().create(UserApi.class);
    private static String token;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.ButtonSingIn).setOnClickListener(view -> {
            login();
        });
    }

    private void login() {
        EditText Login = findViewById(R.id.LoginText);
        EditText Password = findViewById(R.id.PasswordText);
        String name = String.valueOf(Login.getText());
        String password = String.valueOf(Password.getText());

        Response response = new Response();
        response.setUsername(name);
        response.setPassword(password);
        userApi.SingIn(response);
        Call<Token> call = userApi.SingIn(response);
        call.enqueue(new Callback<Token>() {
            @Override
            public void onResponse(Call<Token> call, retrofit2.Response<Token> response) {
                if (response.isSuccessful()) {
                    token = response.body().getToken();
                    String role = response.body().getRole();
                    if (role.equals("[ADMIN]")) {
                        userApi.TokenaAd(token);
                        OpenAdmin();
                    }
                    if (role.equals("[MANAGER]")) {
                        userApi.Manager(token);
                        OpenManager();
                    }
                    if (role.equals("[USER]")) {
                        userApi.Manager(token);
                        OpenUser();
                    }
                } else
                    Toast.makeText(MainActivity.this, "Ошибка входа", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call<Token> call, Throwable t) {
                call.cancel();
            }
        });
    }
public void OpenAdmin(){
        Intent intent = new Intent(this, ActivityAdmin.class);
        startActivity(intent);
}
    public void OpenManager(){
        Intent intent = new Intent(this, ActivityManager.class);
        startActivity(intent);
    }
    public void OpenUser(){
        Intent intent = new Intent(this, ActivityUser.class);
        startActivity(intent);
    }
}

ActivityAdmin.java
package com.example.clientapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ActivityAdmin extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);
    }
    public void CreateActivity(View v) {
        Intent intent = new Intent(this, CreateActivity.class);
        startActivity(intent);
    }
}

activity_admin.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3CD1EC"
    tools:context=".ActivityAdmin">

<Button
     android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginStart="37dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="37dp"
        android:onClick="CreateActivity"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

CreateActivity.java
package com.example.clientapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.clientapp.Model.Product;
import com.example.clientapp.Model.Token;
import com.example.clientapp.retrofit.RetrofitService;
import com.example.clientapp.retrofit.UserApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CreateActivity extends AppCompatActivity {
    private Token tokens;
    private MainActivity mainActivity;
    RetrofitService retrofitService = new RetrofitService();
    UserApi userApi = retrofitService.getRetrofit().create(UserApi.class);

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

        initializeComponents();
    }

    private void initializeComponents() {

        EditText NameP = findViewById(R.id.nameProduct);
        EditText ArticulP = findViewById(R.id.articulProduct);
        EditText QuantityP = findViewById(R.id.quantityProduct);
        EditText PriceP = findViewById(R.id.priceProduct);
        EditText PuPriceP = findViewById(R.id.pupriceProduct);
        Button button = findViewById(R.id.ButtonCreateProduct);


        button.setOnClickListener(view -> {
            String name = String.valueOf(NameP.getText());
            String articul = String.valueOf(ArticulP.getText());
            String quantity = String.valueOf(QuantityP.getText());
            String price = String.valueOf(PriceP.getText());
            String puprice = String.valueOf(PuPriceP.getText());

            Product product = new Product();
            product.getPname(name);
            product.getArticul(articul);
            product.getQuantity(quantity);
            product.getPrice(price);
            product.getPurchasePrice(puprice);
            
            userApi.CreateProduct("JWT токен", product)
                    .enqueue(new Callback<Product>() {
                        @Override
                        public void onResponse(Call<Product> call, Response<Product> response) {
                            if (response.isSuccessful()) {
                                Toast.makeText(CreateActivity.this, "Товар создан", Toast.LENGTH_SHORT).show();
                            } else
                                Toast.makeText(CreateActivity.this, "Ошибка создания товара", Toast.LENGTH_SHORT).show();
                        }
                        @Override
                        public void onFailure(Call<Product> call, Throwable t) {
                            Toast.makeText(CreateActivity.this, "Ошибка", Toast.LENGTH_SHORT).show();
                        }
                    });
        });
    }
        });
    }
}

UserApi.java
package com.example.clientapp.retrofit;


import com.example.clientapp.Model.Product;
import com.example.clientapp.Model.Response;
import com.example.clientapp.Model.Role;
import com.example.clientapp.Model.Token;
import com.example.clientapp.Model.User;
import com.example.clientapp.R;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.PUT;

public interface UserApi {

    @POST("account/register")
    Call<User> RegisterNewUser(@Body User user);
    @POST("jwt/login")
    Call<Token> SingIn(@Body Response response);
    @POST("admin")
    Call<Role>TokenaAd(@Header("Authorization") String access_token);
    @POST("manager")
    Call<Role>Manager(@Header("Authorization") String access_token);
    @POST("user")
    Call<Role>User(@Header("Authorization") String access_token);
    @POST("admin/create")
    Call<Product> CreateProduct(@Header("Authorization:") String access_token, @Body Product product );

Token.java
package com.example.clientapp.Model;

public class Token {
    public String access_token;
    public String Role;

    public String getRole() {
        return Role;
    }

    public void setRole(String role) {
        Role = role;
    }
    public String getToken() {return access_token;}

    public void setToken(String token) {this.access_token = access_token;}
}
  • Вопрос задан
  • 183 просмотра
Пригласить эксперта
Ответы на вопрос 1
vabka
@vabka
Токсичный шарпист
Используй AccountManager
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы