使用Retrofit2调用API以保存和检索JWT令牌

时间:2018-02-22 08:25:17

标签: android jwt retrofit2

我有一个用于生成访客令牌的API

{{url}}/api/token/guest

将令牌返回为:

{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTs4Xk3x-zFfDg5mhYJO7jM8"}

现在我想调用来宾令牌并附加到我的会话中以便我可以访问api中的数据

@GET("/api/properties-latest")
Call<Datum> getNewProperties(@Header("Authorization") String token);

我的会话课程:

   public class Session {
    Context context;
    private SharedPreferences prefs;
    private Session session;
    private ApiInterface apiInterface;
    public Session(Context cntx) {
        // TODO Auto-generated constructor stub
        this.context = cntx;
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
    }



    public void setJwtToken(String token) {

        prefs.edit().putString("token", token).commit();
    }

    public String getJwtToken() {
        String token = prefs.getString("token", "");
        if (token == null || token.isEmpty()) {
            token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
        }
        return token;
    }
    public String getRefreshToken() {
        String token = prefs.getString("RefreshToken", "");
        if (token == null || token.isEmpty()) {
            token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";

        }

        return token;
    }

    public void setRefreshToken(String token) {
        prefs.edit().putString("RefreshToken", token).commit();
    }


}

我的属性方法:

    property_recyclerView = view.findViewById(R.id.new_property_recyclerview);
    property_recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    property_recyclerView.setHasFixedSize(true);
    property_recyclerView.setItemAnimator(new DefaultItemAnimator());
    listener = this;

    Call<Datum> propertyCall = apiInterface.getNewProperties(session.getJwtToken());
    propertyCall.enqueue(new Callback<Datum>() {
        @Override
        public void onResponse(Call<Datum> call, Response<Datum> response) {
            if (response.code() == 200) {
                datum = response.body();

                List<Property> propertyList = datum.getPropertyList();
                propertyAdapter = new PropertyAdapter(propertyList, getContext(), listener);
                property_recyclerView.setAdapter(propertyAdapter);
            }
        }

        @Override
        public void onFailure(Call<Datum> call, Throwable t) {
            Log.e("New Property Fragment", t.getMessage());
        }
    });


    return view;
}

我想访问访客令牌,以便访客用户可以看到这些属性,请帮我找到解决方案。

1 个答案:

答案 0 :(得分:1)

使用SharedPreference访问context,如下所示:

import static android.content.Context.MODE_PRIVATE;

class MyPref {

    private SharedPreferences sp;
    private SharedPreferences.Editor spe;
    Context context;

    public MyPref (Context cntx) {
        // TODO Auto-generated constructor stub
        this.context = cntx;
        sp = context.getSharedPreferences("MyData", MODE_PRIVATE);
        spe = sp.edit();
    }

    public void setJwtToken(String token) {

        spe.putString("token", token).apply();
    }

    public String getJwtToken() {
        String token = sp.getString("token", "");
        if (token == null || token.isEmpty()) {
            token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
        }
        return token;
    }
}

现在可以从您的活动中访问,如下所示:

MyPref m = new MyPref(this);
String tokenToUse = m.getJwtToken();

现在进行Retrofit调用,如下所示:

Call<Datum> call = apiInterface.getNewProperties(tokenToUse);