【问题标题】:how to use interceptor for jwt token如何为 jwt 令牌使用拦截器
【发布时间】:2023-02-06 03:31:38
【问题描述】:

这是我的代码 我的日志说 D/test: user not exist

如何发送 jwt 令牌??

public class ApiClient implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Log.d("test",AccessTokenSharedPreferences.getAccessToken("1"));

        Request request = chain.request()
                .newBuilder()
                .url(BasicInfo.baseUrl)
                .addHeader("X-AUTH-ACCESS-TOKEN", AccessTokenSharedPreferences.getAccessToken("1"))
                .addHeader("X-AUTH-REFRESH-TOKEN", AccessTokenSharedPreferences.getRefreshToken("1"))
                .build();
        Response response = chain.proceed(request);
        return response;
    }

}

谢谢

【问题讨论】:

    标签: java android jwt token interceptor


    【解决方案1】:

    我有同样的问题,但我没有找到适合自己的正确和方便的答案。 但是,我想我有一个适合您的解决方案: 您可以在对服务器发出任何请求之前使用接口 - 侦听器。 也就是说,每次您尝试发送任何授权请求时都会收到一个令牌,并且已经从发送的令牌开始工作。 例如,您想通过授权(在我的例子中是 JWT 持有者令牌)向您的服务器发送一个获取请求。 首先,我声明了一个新接口认证合约:

    public interface AuthentificationContract {
    interface Process{
        void Auth();
        void Auth(String login, String password);
    }
    interface Listener{
        void AuthSuccess(String token);
        void AuthError(String message);
    }}
    

    在哪里过程是由身份验证类实现的接口,您可以在其中向服务器发送请求以接收 JWT 令牌,并且聆听者是一个侦听器,它将根据接收令牌的结果触发主要目标类。 在 Authentication 类中,您实现 Process 接口并实现 Auth 方法以获取令牌。

    public class Authentification implements AuthentificationContract.Process{
    private AuthentificationContract.Listener listener;
    public Authentification(AuthentificationContract.Listener _listener){
      this.listener = _listener;
     }
    @Override
    public void Auth(){
    String token = //your request to get a token
    //when your token arrived:
    listener.AuthSuccess(token);
    //else
    listener.AuthError("ERROR");
    }
    }
    

    重要的!!: 在构造函数中,您必须传递实现 Listener 接口的对象来触发我们的目标类(或视图). 在 View 或 Targer 类中,您应该实现接口 Listener:

    public class StartAcitivity extends AppCompatActivity implements AuthentificationInterface.Listener{
    
    private Authentification auth;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_acitivity);
    
        auth = new Authentification(this);
    
        auth.Auth();
    
    }
    
    @Override
    public void AuthSuccess(String token) {
        //your token is here, you can do request with this token, just add it like one of headers
    }
    
    @Override
    public void AuthError(String message) {
        Log.d("ERROR", message);
    }
    }
    

    当然,这只是一个例子,在视图中执行一些操作并不令人满意,最好使用 MVP 模式

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 2021-05-17
      • 2017-12-31
      • 2017-12-26
      • 2018-06-12
      • 2021-08-04
      • 2019-03-28
      • 2020-05-12
      相关资源
      最近更新 更多