简体   繁体   English

如何在 Android GraphQL 中重新生成令牌?

[英]How to regenerate token in Android GraphQL?

What is the better approach to regenerate the JWT token using refresh token in Apollo Graphql in Andriod Kotlin?.在 Andriod Kotlin 中使用 Apollo Graphql 中的刷新令牌重新生成 JWT 令牌的更好方法是什么?

Now we are using an Auth interceptor that extends ApolloInterceptor to attach the JWT token in the request header.现在我们使用一个扩展 ApolloInterceptor 的 Auth 拦截器,在请求 header 中附加 JWT 令牌。

I want to check whether the Toke expires from here and it should call another mutation to generate a new token.我想检查令牌是否从这里过期,它应该调用另一个突变来生成一个新令牌。 Then it should proceed with the previous call with the new token.然后它应该继续使用新令牌进行先前的调用。

Please refer to the code below请参考下面的代码

  class AuthInterceptor(private val jwtToken: String) : ApolloInterceptor {
        override fun interceptAsync(
            request: ApolloInterceptor.InterceptorRequest,
            chain: ApolloInterceptorChain,
            dispatcher: Executor,
            callBack: ApolloInterceptor.CallBack
        ) {
            val header = request.requestHeaders.toBuilder().addHeader(
                HEADER_AUTHORIZATION,
                "$HEADER_AUTHORIZATION_BEARER $jwtToken"
            ).build()
            chain.proceedAsync(request.toBuilder().requestHeaders(header).build(), dispatcher, callBack)
        }
    
        override fun dispose() {}
    
        companion object {
            private const val HEADER_AUTHORIZATION = "Authorization"
            private const val HEADER_AUTHORIZATION_BEARER = "Bearer"
        }
    }

If you are using Apollo Android Client V3 and Using Kotlin Coroutine then use Apollo Runtime Dependency and Try HttpInterceptor instead of ApolloInterceptor .如果您使用 Apollo Android Client V3 并使用 Kotlin 协程,则使用 Apollo Runtime Dependency 并尝试HttpInterceptor而不是ApolloInterceptor I think this is the better/best approach.我认为这是更好/最好的方法。 For Reference Click Here参考点击这里

In your app-level build.gradle file在您的应用程序级build.gradle文件中

plugins {
......
    id("com.apollographql.apollo3").version("3.5.0")
.....
}

dependencies {
  implementation("com.apollographql.apollo3:apollo-runtime")
}

Now write your interceptor for the Apollo client.现在为 Apollo 客户端编写拦截器。

FYI: If you've added the Authorization header using Interceptor or using addHttpHeader in client already then remove it or don't add header here val response = chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build()) , just build the request.仅供参考:如果您已经使用拦截器或在客户端中使用addHttpHeader添加了Authorization header,则将其删除或不要在此处添加 header val response = chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build()) ,只是构建请求。 Otherwise Authorization header will add multiple times in the request.否则Authorization header 将在请求中添加多次。 So, be careful.所以,要小心。

class AuthorizationInterceptor @Inject constructor(
    val tokenRepo: YourTokenRepo
) : HttpInterceptor {
      private val mutex = Mutex()
    
      override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse {
        var token = mutex.withLock {
          // get current token
        }
    
        val response = chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build())
    
        return if (response.statusCode == 401) {
          token = mutex.withLock {
            // get new token from your refresh token API
          }
          chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build())
        } else {
          response
        }
      }
    }

Configure your Apollo client like below.如下配置您的 Apollo 客户端。

ApolloClient.Builder()
            .httpServerUrl(BASE_GRAPHQL_URL)
            .webSocketServerUrl(BASE_GRAPHQL_WEBSOCKET_ENDPOINT) // if needed
            .addHttpHeader("Accept", "application/json")
            .addHttpHeader("Content-Type", "application/json")
            .addHttpHeader("User-Agent", userAgent)
            .addHttpInterceptor(AuthorizationInterceptor(YourTokenRepo))
            .httpExposeErrorBody(true)
            .build()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当 android 应用程序注销并与其他用户登录时如何重新生成新的 FCM 令牌 - How to regenerate the new FCM Token when android app gets logout and login with another user 是他们手动重新生成推送通知令牌的一种方法(iOS,Android,Windows) - Is their a way to regenerate the push notification token manually (iOS, Android, Windows) 如何在Eclipse中重新生成Android项目的图标? - How to regenerate the icon of android project in eclipse? 如何重新生成 ios 和 android 文件夹? - How can i regenerate ios and android folder? 如何重新生成Resource.designer.cs文件Xamarin Android - How to regenerate Resource.designer.cs file Xamarin Android 如何使用Intellij重新生成android资源文件(R.java) - how to regenerate android resource file (R.java) with working on Intellij 如何重新生成apk? - How to regenerate an apk? 清除网格视图并在android中重新生成 - Clear grid view and regenerate it in android 如何在 Android 上使用 GraphQL 和 Retrofit? - How to use GraphQL with Retrofit on Android? 如何在 React Native 项目版本 0.61.x 中重新生成 Android 和 IOS 文件夹? - How can I regenerate Android and IOS folders in React Native project version 0.61.x?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM