2017-04-20 69 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