2017-04-20 63 views
0

我構建了一個Laravel Passport應用程序。Laravel Passport美孚應用程序訪問

如果我把路由+令牌放在Postman中,它工作得很好,我得到了json數據。

現在什麼是Android應用程序需要訪問這些JSON數據的邏輯。

android應用程序是否需要成功登錄並獲取令牌才能訪問json數據?

如何以編程方式進行此項工作?

當前標記是通過點擊按鈕手動創建的,我怎麼爲它試圖登錄每個Android設備。

自動創建這個我也跟着文檔https://laravel.com/docs/5.4/passport#protecting-routes內置應用程序爲止。但是我的知識在這一點上停止了。

回答

0

Android應用是否需要成功登錄並獲取令牌 才能訪問json數據?

是的,它需要用戶令牌

如何使這項工作程序?

首先,您需要使用護照包在Web服務器Laravel中創建「密碼授權客戶端」。

現在在Android中端,你需要創建signInRequestModel包含您的申請信息:

public class SignInRequestModel { 
    public String client_id; 
    public String client_secret; 
    public String username; 
    public String password; 
    public String grant_type="password"; 

    public SignInRequestModel() { 
     this.client_id = Config.CLIENT_ID; 
     this.client_secret = Config.CLIENT_SECRET; 
    } 
} 

和創建登錄方法,將調用登錄服務

private void login() { 
     SignInRequestModel signInRequestModel = new SignInRequestModel(); 
     signInRequestModel.username = this.email; //User email 
     signInRequestModel.password = this.password; // User Password 
     //provide service 
     ServiceGenerator provider = new ServiceGenerator(); 
     ProjectService tService = provider.getService(); 
     //make call 
     appPreferenceTools = new AppPreferenceTools(LoginActivity.this); 
     Call<AuthenticationResponseModel> call = tService.signIn(signInRequestModel); 
     progressBar.setVisibility(View.VISIBLE); 
     call.enqueue(new Callback<AuthenticationResponseModel>() { 
      @Override 
      public void onResponse(Call<AuthenticationResponseModel> call, Response<AuthenticationResponseModel> response) { 
       if (response.isSuccessful()) { 
        appPreferenceTools.saveUserAuthenticationInfo(response.body()); //save user token 
        Snackbar.make(parent_view, "Login Success", Snackbar.LENGTH_SHORT).show(); 
        // ToDo Your Code 
      } 

      @Override 
      public void onFailure(Call<AuthenticationResponseModel> call, Throwable t) { 
       //occur when fail to deserialize || no network connection || server unavailable 
       Log.d(TAG, t.getMessage() + " " + t.getCause()); 
      } 


     }); 

    } 

ServiceGenerator類將生成您的服務,並會工作將用戶標記添加到標題請求並在需要時獲取刷新標記。

public class ServiceGenerator { 

    private ProjectService mTService; 
    private Retrofit mRetrofitClient; 
    private AppPreferenceTools tools; // PreferenceTools for Your Project 
    private OkHttpClient.Builder httpClient; 

    public ServiceGenerator() { 
     tools = new AppPreferenceTools(App.getContext()); 

     httpClient = new OkHttpClient.Builder(); 

     /* you need */ 
     HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // for debug 
     logging.setLevel(HttpLoggingInterceptor.Level.BODY); // for debug 
     httpClient.addInterceptor(logging); // for debug 


     httpClient.authenticator(new Authenticator() { 
      @Override 
      public Request authenticate(Route route, Response response) throws IOException { 
       if (tools.isAuthorized()) { 
        //make the refresh token request model 
        RefreshTokenRequestModel requestModel = new RefreshTokenRequestModel(); 
        requestModel.refresh_token = tools.getRefreshToken(); 
        //make call 
        Call<AuthenticationResponseModel> call = mTService.getRefreshModel(requestModel); 
        retrofit2.Response<AuthenticationResponseModel> tokenModelResponse = call.execute(); 
        if (tokenModelResponse.isSuccessful()) { 
         tools.saveUserAuthenticationInfo(tokenModelResponse.body()); 
         System.out.println(tokenModelResponse.body()); 
         return response.request().newBuilder() 
           .removeHeader("Authorization") 
           .addHeader("Authorization", "Bearer " + tools.getAccessToken()) 
           .build(); 
        } else { 
         return null; 
        } 
       } else { 
        return null; 
       } 
      } 
     }); 


     httpClient.addInterceptor(new Interceptor() { 
      @Override 
      public Response intercept(Chain chain) throws IOException { 
       Request orginal = chain.request(); 
       Request.Builder builder = orginal.newBuilder(); 
       builder.addHeader("Accept", "application/json"); 
       if (tools.isAuthorized()) { 
        builder.addHeader("Authorization", "Bearer " + tools.getAccessToken()); 
       } 
       builder.method(orginal.method(), orginal.body()); 
       Request build = builder.build(); 
       return chain.proceed(build); 
      } 
     }); 

     //create new gson object to define custom converter on Date type 
     Gson gson = new GsonBuilder() 
       .create(); 

     mRetrofitClient = new Retrofit.Builder() 
       .baseUrl(Config.AP_URL_BASE) // set Base URL , should end with '/' 
       .client(httpClient.build()) // add http client 
       .addConverterFactory(GsonConverterFactory.create(gson))//add gson converter 
       .build(); 
     mTService = mRetrofitClient.create(ProjectService.class); 

    } 

    public ProjectService getService() { 
     return mTService; 
    } 

    public Retrofit getmRetrofitClient() { 
     return mRetrofitClient; 
    } 

} 

最後你需要爲你的路由創建界面:

public interface ProjectService { 
    @POST("oauth/token") 
    Call<AuthenticationResponseModel> signIn(@Body SignInRequestModel signInRequestModel); 
// Todo Refresh Token ,sign Up 

} 

包,你將需要:

compile 'com.squareup.retrofit2:retrofit:2.1.0' 
    compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
    compile 'com.squareup.okhttp3:logging-interceptor:3.5.0' 
+0

謝謝你的答案目前我沒有時間來測試這一點,我可能會在10天左右回覆你。 – utdev