Jwt令牌刷​​新?

时间:2018-02-19 09:41:25

标签: android retrofit2

我有一个用于刷新令牌的API,但我无法在我的应用中使用刷新令牌,用户登录令牌在60分钟后过期,所以现在我想刷新用户令牌,我该如何使用刷新我的应用中的令牌 我的刷新令牌界面:

@POST("/api/token/refresh")
Call<ResponseBody> getAccessToken();

我的会议:

public class Session {
Context context;
private SharedPreferences prefs;
private Session session;

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";

        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
        Call<ResponseBody> call = apiInterface.getAccessToken();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                JSONObject resultObject = new JSONObject();
                JSONObject tokenObject = null;
                try {
                    tokenObject = resultObject.getJSONObject("token");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String newToken = null;
                try {
                    newToken = tokenObject.getString("accessToken");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                newToken = "Bearer " + newToken;
                session.setJwtToken(newToken);
                Log.e("Token Result Object", session.getJwtToken());
                Log.e("Token Response Object", session.getRefreshToken());
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

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

我的登录信息:

public class LoginActivity extends AppCompatActivity {
private Button userLogin;
ApiInterface apiInterface;
private EditText loginEmail, loginPassword;
private User user;

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

    loginEmail = findViewById(R.id.loginEmail);

    loginPassword = findViewById(R.id.loginPassword);

    userLogin = findViewById(R.id.loginButton);

    userLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            userLogin();

        }
    });

    TextView register = (TextView) findViewById(R.id.register);
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
            startActivity(intent);
        }
    });


    ImageView back = (ImageView) findViewById(R.id.back_arrow_login);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
}

public void userLogin() {
    final User user = new User();
    final Session session = new Session(this);
    user.setEmail(loginEmail.getText().toString().trim());
    user.setPassword(loginPassword.getText().toString().trim());
    apiInterface = ApiClient.getClient().create(ApiInterface.class);

    Call<ResponseBody> call = apiInterface.logMeIn(session.getJwtToken(),user);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.code() == 200) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    String token = dataObject.getString("access_token");
                    String refToken = dataObject.getString("refresh_token");
                    session.setJwtToken("Bearer " + token);
                    session.setRefreshToken("Bearer"+refToken);
                    String name=user.getName();
                    Toast.makeText(LoginActivity.this, "WELCOME", Toast.LENGTH_SHORT).show();
                    Log.e("USER", jsonObject.toString());
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));


                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else
                Log.e("TestActivity", response.raw().toString());

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    });

}
}

请帮我清除方法或流程,以便我可以在用户令牌过期后刷新用户令牌

1 个答案:

答案 0 :(得分:0)

public class ServiceFactory {

private static final long CONNECTION_TIMEOUT = 60 * 1000; // one minute
private Activity activity;

public ServiceFactory(Activity activity) {
    this.activity = activity;
}

public static <T> T createService(final Class<T> clazz) {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())

            .build();

    return retrofit.create(clazz);
}

public  <T> T createServiceWithToken(final Class<T> clazz) {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .client(getHttpClientBuilder())
            .addConverterFactory(GsonConverterFactory.create())

            .build();

    return retrofit.create(clazz);
}



private  OkHttpClient getHttpClientBuilder() {
    // Setup OkHttpClient
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
            .readTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
            .writeTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
            .authenticator(new TokenAuthenticator());

    return builder.build();
}

private void logout() {
    if (activity != null) {
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
        activity.finish();
    }
}

 class TokenAuthenticator implements Authenticator {

    @Nullable
    @Override
    public Request authenticate(@NonNull Route route, @NonNull Response response) throws IOException {
        TokenManager tokenManager = new TokenManager();

        //called renew api call
        retrofit2.Response<ResponseModel> responseModel= ServiceFactory.createService(YOUR_API.class)
                .renewToken(tokenManager.getBearer())
                .execute();

        if (responseModel.code() == 401) {
        //remove token
            logout();
            return null;
        } else {
            //saved token to local

        }

        //returned new reuwst with updated header
        return response.request().newBuilder()
                .header(APIConstants.AUTHORIZATION, tokenManager.getBearer())
                .build();
    }
}

}