oauth2用dagger2android刷新

vlju58qv  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(426)

我正在尝试用dagger2实现oauth2登录。一旦access\u token过期,我已经通过refresh\u token成功地生成了新的access\u token,但是一旦refresh\u token也过期,验证器就会进入无限循环。
这是我的网络模块,我在okhttp客户端中定义了身份验证器和拦截器

@Module
   public class NetworkModule
   {
       @Provides
       @Singleton
       OkHttpClient provideOkHttpClient(TokenAuthenticator tokenAuthenticator, TokenInceptor tokenInceptor, SharedManager sharedManager)
       {
           HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
          logging.setLevel(HttpLoggingInterceptor.Level.BODY);

           OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
           // adding socket time for read/write/reconnect
           httpClient.connectTimeout(30, TimeUnit.SECONDS);
           httpClient.writeTimeout(30, TimeUnit.SECONDS);
           httpClient.readTimeout(30, TimeUnit.SECONDS);
           // setting the accept type of the request to application/json
           httpClient.addNetworkInterceptor(new Interceptor()
           {
               @Override
               public Response intercept(Chain chain) throws IOException {
                   Request.Builder requestBuilder = chain.request().newBuilder();
                   requestBuilder.header("Accept", "application/json");
                   return chain.proceed(requestBuilder.build());
              }
           });
           httpClient.addInterceptor(logging).addInterceptor(tokenInceptor);
           httpClient.authenticator(tokenAuthenticator);
           return httpClient.build();
       }
    }

       @Provides
       Retrofit provideRetrofit(OkHttpClient okHttpClient){
           return new Retrofit.Builder()
            .baseUrl(ApiConstants.API_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(okHttpClient)
            .build();
       }

       @Provides
       @Singleton
       ApiService provideApiService(Retrofit retrofit, TokenService apiServiceHolder)
       {
           ApiService apiService = retrofit.create(ApiService.class);
           apiServiceHolder.setApiService(apiService);
           return apiService;
       }

       @Provides
       @Singleton
       public SharedPreferences providePreferences(Application application)
       {
           return application.getSharedPreferences(Constants.APP_PREFERENCES, Context.MODE_PRIVATE);
       }

       @Provides
       @Singleton
       public SharedManager provideSharedManager(SharedPreferences sharedPreferences)
       {
           return new SharedManager(sharedPreferences);
       }

       @Provides
       @Singleton
       public TokenAuthenticator tokenAuthenticator(TokenService tokenService, SharedManager sharedManager)
       {
           return new TokenAuthenticator(tokenService, sharedManager);
       }

       @Provides
       @Singleton
       public TokenInceptor tokenInceptor(SharedManager sharedManager)
       {
           return new TokenInceptor(sharedManager);
       }

       @Provides
       @Singleton
       public TokenService apiServiceHolder()
       {
    return new TokenService();
       }
   }

这是拦截器

@Singleton
   public class TokenInceptor implements Interceptor
   {
       SharedManager sharedManager;
       @Inject
       public TokenInceptor(SharedManager sharedManager)
       {
           this.sharedManager = sharedManager;
       }
       @Override
       public Response intercept(Chain chain) throws IOException
       {
           Request request = chain.request();

           // we don't need header in login/register so, we remove the header from these api request endpoints
           if(request.url().encodedPath().contains("/token/client") && request.method().equalsIgnoreCase("POST"))
           {
               return chain.proceed(request);
           }

           // then we add the authenticator to other api requests
           HttpUrl url = request.url();
           Request.Builder urlBuilder = request.newBuilder().addHeader(ApiConstants.AUTHORIZATION, sharedManager.getBearer()).url(url);
           Request apiRequest = urlBuilder.build();
           return chain.proceed(apiRequest);
       }
   }

这是验证者

@Singleton
    public class TokenAuthenticator implements Authenticator
    {
        private SharedManager sharedManager;
        private TokenService tokenService;

        @Inject
        public TokenAuthenticator(@NonNull TokenService apiServiceHolder, SharedManager sharedManager)
        {
            this.tokenService = apiServiceHolder;
            this.sharedManager = sharedManager;
        }

        @Nullable
        @Override
        public Request authenticate(Route route, Response response) throws IOException
        {
            if(!response.request().header(ApiConstants.AUTHORIZATION).equals(sharedManager.getBearer()))
            {
                return null;
            }

            retrofit2.Response<TokenResponse> tokenResponse = tokenService.getApiService().refreshToken(sharedManager.getRefresh()).execute();

            TokenResponse responseData = tokenResponse.body();

            if(tokenResponse.isSuccessful() && responseData!= null)
            {
                TokenResponse responseRequest = (TokenResponse) tokenResponse.body();
                String new_token = responseRequest.getAccess();
                sharedManager.saveAccessToken(new_token);
                return response.request().newBuilder().header(ApiConstants.AUTHORIZATION,sharedManager.getBearer()).build();
            }
            else
            {
                // As per my assumption, the refresh token might expire here
                Log.e("refresh_token","expired");
            }
            return null;
        }
    }

下面是tokenservice类

public class TokenService
   {
       ApiService apiService = null;

       @Nullable
       public ApiService getApiService() {
           return apiService;
       }

       public void setApiService(ApiService apiService) {
           this.apiService = apiService;
       }
   }

这是sharedmanager类

public class SharedManager
    {
        private SharedPreferences sharedPreferences;
        @Inject
        public SharedManager(SharedPreferences sharedPreferences)
        {this.sharedPreferences = sharedPreferences;};

        public void saveAccessToken(String token)
        {
            sharedPreferences.edit().putString(ApiConstants.ACCESS_TOKEN, token).commit();
        }
        public void saveRefreshToken(String token)
        {
            sharedPreferences.edit().putString(ApiConstants.REFRESH, token).commit();
        }
        public String getAccessToken()
        {
            return sharedPreferences.getString(ApiConstants.ACCESS_TOKEN, "");
        }
        public String getRefresh()
        {
            return sharedPreferences.getString(ApiConstants.REFRESH, "");
        }
        public String getBearer()
        {
           return "Bearer "+getAccessToken();
        }
        public void clearAll()
        {
            sharedPreferences.edit().clear().commit();
        }
    }

这是apiservice接口

public interface ApiService
   {
       // client login
       @POST("token/client")
       @FormUrlEncoded
       Call<ResponseBody> loginUser(@Field("email") String email,
                             @Field("password") String password);

       // method for refresh token
       @POST("token/refresh")
       @FormUrlEncoded
       Call<TokenResponse> refreshToken(@Field("refresh") String refresh);

         // get agent
       @GET("agent")
       Call<ResponseBody> getAgentTour();

   }

有人能找出代码中的错误吗?在堆栈中过帐时,代码结构已更改。

ldxq2e6h

ldxq2e6h1#

当刷新令牌最终过期时,标准刷新令牌授予消息将返回无效的\u授予的错误代码。

{
  "error": "invalid_grant",
  "error_description": "An optional description message that varies between vendors"
}

在这一点上,你应该做两件事:
对于任何飞行中的api调用,抛出一个异常,其中包含一个错误代码,例如“login\u required”,错误处理代码可以自动忽略该异常
然后执行登录重定向以启动新的用户会话
我的样本代码
作为比较,我有一个appauth代码示例,您可以运行它,它允许模拟令牌过期事件:
处理无效授权的android代码
android代码示例博客文章
当然,您需要将这种行为转化为您自己的基于匕首的编码首选项。。。

相关问题