Retrofit2授权-访问令牌的全局拦截器


76

我正在尝试使用Retrofit2,我想添加Token到我的Header像这样:

Authorization: Bearer Tokencode以下内容不起作用:

public interface APIService {
    @Headers({"Authorization", "Bearer "+ token})
    @GET("api/Profiles/GetProfile?id={id}")
    Call<UserProfile> getUser(@Path("id") String id);
}

我的服务器是asp.net webApi。请帮我该怎么办?


只有在“令牌”是编译时间常数时,这种添加标头的方式才有效。Java的注释规则等。文档提供了另一种包括标头的方法:square.github.io/retrofit(使其成为方法参数)
zapl

Answers:


133

您有两种选择-您可以将其添加为通话参数-

@GET("api/Profiles/GetProfile?id={id}")
Call<UserProfile> getUser(@Path("id") String id, @Header("Authorization") String authHeader);

这可能有点烦人,因为您必须"Bearer" + token在每次通话中传递。如果您没有太多需要令牌的呼叫,则此方法很适合。

如果您想将标头添加到所有请求,则可以使用okhttp拦截器-

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {
        Request newRequest  = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer " + token)
            .build();
        return chain.proceed(newRequest);
      }
    }).build();

Retrofit retrofit = new Retrofit.Builder()
    .client(client)
    .baseUrl(/** your url **/)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

1
对我来说,我不知道,直到我实现它,但令牌只知道在运行时-因此,我认为这是一个更好的解决方案:stackoverflow.com/questions/43051558/...
丹尼尔·威尔逊

感谢其用于承载令牌的工作,但是感谢如何使用dyanamic标头添加FieldMap。我已经尝试过使用FieldMap,但是它不起作用。请帮助。
Dildarkhan Pathan

第一个案例:“ Bearer” +令牌。“载体” +令牌。需要空白空间
cristianego

22

如果要添加承载令牌作为标头,则可以执行这些类型的过程。

这是使用Bearer令牌的一种方法

在界面中

@Headers({ "Content-Type: application/json;charset=UTF-8"})
@GET("api/Profiles/GetProfile")
Call<UserProfile> getUser(@Query("id") String id, @Header("Authorization") String auth);

之后,您将以这种方式调用Retrofit对象

Retrofit retrofit  = new Retrofit.Builder()
                    .baseUrl("your Base URL")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

APIService client = retrofit.create(APIService.class);
Call<UserProfile> calltargetResponse = client.getUser("0034", "Bearer "+token);
calltargetResponse.enqueue(new Callback<UserProfile>() {
       @Override
       public void onResponse(Call<UserProfile> call, retrofit2.Response<UserProfile> response) {
           UserProfile UserResponse = response.body();
           Toast.makeText(this, " "+response.body(), Toast.LENGTH_SHORT).show();
                }
        @Override
        public void onFailure(Call<UserProfile> call, Throwable t) {
            //Toast.makeText(this, "Failed ", Toast.LENGTH_SHORT).show();
        }
});

另一种方法是使用拦截,这与先前的答案类似。但是,那时候您只需要稍微修改一下接口即可。

@Headers({ "Content-Type: application/json;charset=UTF-8"})
@GET("api/Profiles/GetProfile")
Call<UserProfile> getUser(@Query("id") String id); 

希望这对您有用。


10

基于@Daniel Wilson建议的具有不同类和结构的@iagreen解决方案kotlin版本

使Retrofit实例像这样

object RetrofitClientInstance {
   private var retrofit: Retrofit? = null
   private val BASE_URL = "http://yoururl"


    val retrofitInstance: Retrofit?
        get() {
            if (retrofit == null) {
                var client = OkHttpClient.Builder()
                      .addInterceptor(ServiceInterceptor())
                      //.readTimeout(45,TimeUnit.SECONDS)
                      //.writeTimeout(45,TimeUnit.SECONDS)
                        .build()

                retrofit = Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()

            }
            return retrofit
      }

}

ServiceInterceptor如下添加类

class ServiceInterceptor : Interceptor{

  var token : String = "";

  fun Token(token: String ) {
     this.token = token;
  }

  override fun intercept(chain: Interceptor.Chain): Response {
    var request = chain.request()

    if(request.header("No-Authentication")==null){
        //val token = getTokenFromSharedPreference();
        //or use Token Function
        if(!token.isNullOrEmpty())
        {
            val finalToken =  "Bearer "+token
            request = request.newBuilder()
                    .addHeader("Authorization",finalToken)
                    .build()
        }

    }

    return chain.proceed(request)
  }

}

登录界面和数据类实现

interface Login {
  @POST("Login")
  @Headers("No-Authentication: true")
  fun login(@Body value: LoginModel): Call<LoginResponseModel>



  @POST("refreshToken")
  fun refreshToken(refreshToken: String): 
      Call<APIResponse<LoginResponseModel>>
}

data class LoginModel(val Email:String,val Password:String)
data class LoginResponseModel (val token:String,val 
         refreshToken:String)

在任何这样的活动中称呼它

val service = RetrofitClientInstance.retrofitInstance?.create(Login::class.java)
val refreshToken = "yourRefreshToken"
val call = service?.refreshToken(refreshToken)
        call?.enqueue(object: Callback<LoginResponseModel>{
            override fun onFailure(call: Call<LoginResponseModel>, t: Throwable) {
                print("throw Message"+t.message)
                Toast.makeText(applicationContext,"Error reading JSON",Toast.LENGTH_LONG).show()
            }

            override fun onResponse(call: Call<LoginResponseModel>, response: Response<LoginResponseModel>) {
                val body = response?.body()
                if(body!=null){
                    //do your work
                }
            }

        })

有关详细信息,视频将有所帮助。


4

这会将您的令牌添加到构建器中,您可以在登录/注销的情况下随时更改它。

object ApiService {
    var YOUR_TOKEN = ""

    private var retrofit: Retrofit = Retrofit.Builder()
        .baseUrl("YOUR_URL")
        .addConverterFactory(GsonConverterFactory.create())
        .client(OkHttpClient.Builder().addInterceptor { chain ->
            val request = chain.request().newBuilder().addHeader("Authorization", "Bearer ${YOUR_TOKEN}").build()
            chain.proceed(request)
        }.build())
        .build()

    var service: AppAPI = retrofit.create(AppAPI::class.java)
        private set

}

这是否意味着每次令牌更改时都必须调用Retrofit.Builder()?我以为我先构建了Retrofit,然后登录,登录后我使用令牌直到令牌过期。我还不明白。:)
令人难以置信的1

1

您将需要在中添加拦截器OkHttpClient

添加一个名为的类OAuthInterceptor

class OAuthInterceptor(private val tokenType: String, private val accessToken: String) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", "$tokenType $accessToken").build()

        return chain.proceed(request)
    }
}

之后,初始化RetrofitApiService接口时,将需要此接口。

interface RetrofitApiService {
    companion object {
        private const val BASE_URL = "https://api.coursera.org/api/businesses.v1/"
        fun create(accessToken: String): RetrofitApiService {
            val client = OkHttpClient.Builder()
                    .addInterceptor(OAuthInterceptor("Bearer", accessToken))
                    .build()

            val retrofit = Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .client(client)
                    .build()

            return retrofit.create(RetrofitApiService::class.java)
        }
    }
}

向Java Code Monk大喊大叫,并访问参考链接以获取更多详细信息。 https://www.javacodemonk.com/retrofit-oauth2-authentication-okhttp-android-3b702350

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.